如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
使用Open XML SDK 2.0 for Microsoft Office怎么样?
一些好处:
不需要安装Office由Microsoft制作=像样的MSDN文档只有一个.Net dll可用于项目SDK附带了许多工具,如diff、验证器等
链接:
githubMSDN主登录“How Do I…”起始页blogsMSDN brian_jones发布SDKblogs.MSDN brian_jones描述SDK处理大型文件而不崩溃(与DOM方法不同)
其他回答
我想知道为什么没有人建议PowerShell使用免费的ImportExcel模块;它可以轻松创建XML Excel文件(xlsx)。
从SQL Server等数据库创建Excel工作表时尤其容易。。。
您可以使用此库创建格式良好的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};
}
}
前段时间,我在NPOI上创建了一个DLL。使用它非常简单:
IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople);
MemoryStream memory = engine.Export();
你可以在这里阅读更多。
顺便说一句,它是100%开源的。随时使用、编辑和共享;)
您可以在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
好
也可以使用Aspose这样的第三方库。
此库的优点是它不需要在您的计算机上安装Excel,这在您的情况下是理想的。
推荐文章
- .NET中的Map和Reduce
- 我如何能使一个组合框不可编辑的。net ?
- .NET反射的成本有多高?
- 实体框架回滚并移除不良迁移
- 将流转换为字符串并返回
- 在c#中检查字符串是否只包含数字的最快方法
- IEquatable和重写Object.Equals()之间的区别是什么?
- 创建一个堆栈大小为默认值50倍的线程有什么危险?
- 转换JSON字符串到JSON对象c#
- .text, .value和.value2之间的区别是什么?
- 显示两个datetime值之间的小时差值
- 如何设置enum为空
- 选择Enum类型的默认值而无需更改值
- 我如何设置在一个组合框中选择的项目,以匹配我的字符串使用c# ?
- String与StringBuilder