如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
OpenXML也是一个很好的选择,它有助于避免在服务器上安装MS Excel。Microsoft提供的Open XML SDK 2.0简化了操作Open XML包和包中的底层Open XML架构元素的任务。开放式XML应用程序编程接口(API)封装了开发人员在开放式XML包上执行的许多常见任务。
看看OpenXML:有助于避免在服务器上安装MS Excel的替代方案
其他回答
您可以在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
我成功地使用了以下开源项目:
用于OOXML格式的ExcelPackage(Office 2007)XLS格式的NPOI(Office 2003)。NPOI 2.0(Beta版)也支持XLSX。
看看我的博客帖子:
在C中创建Excel电子表格.XLS和.XLSX#
带有Excel表格和动态图表的NPOI
您可以使用此库创建格式良好的Excel文件:http://officehelper.codeplex.com/documentation参见以下示例:
using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
helper.CurrentSheetName = "Sheet1";
helper.CurrentPosition = new CellRef("C3");
//the template xlsx should contains the named range "header"; use the command "insert"/"name".
helper.InsertRange("header");
//the template xlsx should contains the named range "sample1";
//inside this range you should have cells with these values:
//<name> , <value> and <comment>, which will be replaced by the values from the getSample()
CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"});
helper.InsertRange(sample1, getSample());
//you could use here other named ranges to insert new cells and call InsertRange as many times you want,
//it will be copied one after another;
//even you can change direction or the current cell/sheet before you insert
//typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
helper.DeleteSheet("Sheet3");
}
示例如下:
private IEnumerable<List<object>> getSample()
{
var random = new Random();
for (int loop = 0; loop < 3000; loop++)
{
yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
}
}
检查一下,不需要第三方库,您可以使用以下命令将数据表数据导出到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();
一个非常轻量级的选项可能是使用HTML表。只需在文件中创建head、body和table标记,然后将其另存为扩展名为.xls的文件。您可以使用Microsoft特定的属性来设置输出样式,包括公式。
我意识到,您可能没有在web应用程序中对此进行编码,但这里有一个通过HTML表组成Excel文件的示例。如果您正在编写控制台应用程序、桌面应用程序或服务,则可以使用此技术。
推荐文章
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- Java:路径vs文件
- 组合框:向项目添加文本和值(无绑定源)
- AutoMapper:“忽略剩下的?”
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接
- 如何使用。net 4运行时运行PowerShell ?
- 在foreach循环中编辑字典值