如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
如果您从代码中创建数据表或数据网格视图,则可以使用此简单方法保存所有数据。不建议使用此方法,但它可以100%工作,即使您没有在计算机中安装MS Excel。
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
saveFileDialog1.FileName = "Employee Details.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fname = saveFileDialog1.FileName;
StreamWriter wr = new StreamWriter(fname);
for (int i = 0; i <DataTable.Columns.Count; i++)
{
wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (DataTable.Rows.Count); i++)
{
for (int j = 0; j < DataTable.Columns.Count; j++)
{
if (DataTable.Rows[i][j] != null)
{
wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
}
catch (Exception)
{
MessageBox.Show("Error Create Excel Sheet!");
}
其他回答
我使用了几个选项:
如果XLSX是必须的:ExcelPackage是一个很好的开始,但当开发人员停止工作时就夭折了。ExML不是一个坏选项,我仍在一些生产网站上使用它。
不过,对于我的所有新项目,我都使用NPOI,即Apache POI的.NET端口。NPOI 2.0(Alpha)也支持XLSX。
您可以在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
如果您从代码中创建数据表或数据网格视图,则可以使用此简单方法保存所有数据。不建议使用此方法,但它可以100%工作,即使您没有在计算机中安装MS Excel。
try
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel Documents (*.xls)|*.xls";
saveFileDialog1.FileName = "Employee Details.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string fname = saveFileDialog1.FileName;
StreamWriter wr = new StreamWriter(fname);
for (int i = 0; i <DataTable.Columns.Count; i++)
{
wr.Write(DataTable.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (DataTable.Rows.Count); i++)
{
for (int j = 0; j < DataTable.Columns.Count; j++)
{
if (DataTable.Rows[i][j] != null)
{
wr.Write(Convert.ToString(getallData.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
}
catch (Exception)
{
MessageBox.Show("Error Create Excel Sheet!");
}
各种Office 2003 XML库适用于较小的excel文件。然而,我发现以XML格式保存的大型工作簿的大小是一个问题。例如,我使用的新XLSX格式的工作簿将是40MB(当然也更紧凑),它将变成360MB的XML文件。
就我的研究而言,有两个商业软件包允许输出到较旧的二进制文件格式。他们是:
宝石盒ComponentOne Excel
两者都不便宜(我认为分别为500美元和800美元)。但两者都独立于Excel本身。
我会好奇的是OpenOffice.org之类的Excel输出模块。我想知道它们是否可以从Java移植到.Net。
前段时间,我在NPOI上创建了一个DLL。使用它非常简单:
IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople);
MemoryStream memory = engine.Export();
你可以在这里阅读更多。
顺便说一句,它是100%开源的。随时使用、编辑和共享;)
推荐文章
- 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循环中编辑字典值