如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?


当前回答

我使用了几个选项:

如果XLSX是必须的:ExcelPackage是一个很好的开始,但当开发人员停止工作时就夭折了。ExML不是一个坏选项,我仍在一些生产网站上使用它。

不过,对于我的所有新项目,我都使用NPOI,即Apache POI的.NET端口。NPOI 2.0(Alpha)也支持XLSX。

其他回答

我也投票支持GemBox.Spreadsheet。

非常快速且易于使用,网站上有大量示例。

以全新的执行速度完成了我的报告任务。

一些第三方组件供应商,如Infregistics或Syncfusion,提供了非常好的Excel导出功能,不需要安装Microsoft Excel。

由于这些供应商还提供高级UI网格组件,如果您希望excel导出的样式和布局模拟应用程序用户界面中网格的当前状态,这些组件特别方便。

如果您的导出是在服务器端执行的,重点是要导出的数据,并且没有到UI的链接,那么我会选择一个免费的开源选项(例如ExcelLibrary)。

我以前参与过一些试图在Microsoft Office套件上使用服务器端自动化的项目。根据这一经验,我强烈建议反对这种做法。

您可以在Visual Studio上安装OpenXml nuget包。以下是将数据表导出到excel文件的代码:

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet

Public Class ExportExcelClass
    Public Sub New()

    End Sub

    Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)
        ' Create a spreadsheet document by supplying the filepath.
        ' By default, AutoSave = true, Editable = true, and Type = xlsx.
        Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)

        ' Add a WorkbookPart to the document.
        Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPart
        workbook.Workbook = New Workbook

        ' Add a WorksheetPart to the WorkbookPart.
        Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()
        Worksheet.Worksheet = New Worksheet(New SheetData())

        ' Add Sheets to the Workbook.
        Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())

        Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()
        Dim Header As Row = New Row()
        Header.RowIndex = CType(1, UInt32)

        For Each column As DataColumn In table.Columns
            Dim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)
            Header.AppendChild(headerCell)
        Next

        data.AppendChild(Header)

        Dim contentRow As DataRow
        For i As Integer = 0 To table.Rows.Count - 1
            contentRow = table.Rows(i)
            data.AppendChild(createContentRow(contentRow, i + 2))
        Next

    End Sub

    Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As Cell
        Dim cell As Cell = New Cell()
        cell.DataType = CellValues.InlineString

        cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString

        Dim inlineString As InlineString = New InlineString()
        Dim t As Text = New Text()
        t.Text = cellValue.ToString()
        inlineString.AppendChild(t)
        cell.AppendChild(inlineString)
        Return cell
    End Function

    Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As Row
        Dim row As Row = New Row With {
            .rowIndex = CType(rowIndex, UInt32)
        }

        For i As Integer = 0 To dataRow.Table.Columns.Count - 1
            Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))
            row.AppendChild(dataCell)
        Next

        Return row
    End Function

    Private Function getColumnName(ByVal columnIndex As Integer) As String
        Dim dividend As Integer = columnIndex
        Dim columnName As String = String.Empty
        Dim modifier As Integer

        While dividend > 0
            modifier = (dividend - 1) Mod 26
            columnName = Convert.ToChar(65 + modifier).ToString() & columnName
            dividend = CInt(((dividend - modifier) / 26))
        End While

        Return columnName
    End Function
End Class

检查一下,不需要第三方库,您可以使用以下命令将数据表数据导出到excel文件

var dt = "your code for getting data into datatable";
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
            {
                Response.Write(tab + dataColumn.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dataRow in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dataRow[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();

这里有一个完全免费的C#库,它允许您使用OpenXML库从DataSet、DataTable或List<>导出到真正的Excel 2007.xlsx文件中:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

免费提供完整的源代码以及说明和演示应用程序。

将此类添加到应用程序后,只需一行代码即可将DataSet导出到Excel:

CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

没有比这更简单的了。。。

它甚至不需要Excel出现在您的服务器上。