如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
下面是使用LINQ to XML完成此操作的方法,并提供示例代码:
用LINQ to XML快速导入和导出Excel数据
它有点复杂,因为您必须导入名称空间等等,但它确实可以避免任何外部依赖。
(当然,它是VB.NET,而不是C#,但您可以始终在自己的项目中隔离VB.NET内容,以使用XML文字,并使用C#执行其他所有操作。)
其他回答
您可以使用OLEDB创建和操作Excel文件。选中此项:使用OLEDB读写Excel。
典型示例:
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
cmd.ExecuteNonQuery();
}
编辑-更多链接:
嘿,脚本人!如何在不使用Excel的情况下从Excel读取?如何使用ADO.NET在Visual Basic.NET中检索和修改Excel工作簿中的记录使用ADO.NET C#DbProviderFactory读写Excel电子表格
Java开源解决方案是Apache POI。也许这里有一种设置互操作的方法,但我对Java的了解不够,无法回答这个问题。
当我探索这个问题时,我最终使用了互操作程序集。
如何在OneDrive上使用C#创建Excel(.xslx)文件而不安装Microsoft Office
Microsoft Graph API提供文件和Excel API,用于为企业和消费者帐户创建和修改存储在OneDrive中的Excel文件。Microsoft.Graph NuGet包提供了许多用于使用File和Excel API的接口。
{
Name = "myExcelFile.xslx",
File = new Microsoft.Graph.File()
};
// Create an empty file in the user's OneDrive.
var excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);
// Add the contents of a template Excel file.
DriveItem excelDriveItem;
using (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))
{
//Upload content to the file. ExcelTestResource is an empty template Excel file.
//https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent
excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);
}
此时,您现在已经在用户(企业或消费者)或组的OneDrive中创建了一个Excel文件。现在,您可以使用Excel API对Excel文件进行更改,而无需使用Excel,也无需了解Excel XML格式。
我重新编码了代码,现在可以创建.xls文件,稍后可以转换为Excel 2003 Open XML格式。
private static void exportToExcel(DataSet source, string fileName)
{
// Documentacion en:
// https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
// https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db
// https://riptutorial.com/es/openxml
const string startExcelXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
"<?mso-application progid=\"Excel.Sheet\"?>\r\n" +
"<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
"xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n " +
"xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n " +
"xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n " +
"xmlns:html=\"https://www.w3.org/TR/html401/\">\r\n " +
"<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
" <Version>16.00</Version>\r\n " +
"</DocumentProperties>\r\n " +
" <OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n " +
" <AllowPNG/>\r\n " +
" </OfficeDocumentSettings>\r\n " +
" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n " +
" <WindowHeight>9750</WindowHeight>\r\n " +
" <WindowWidth>24000</WindowWidth>\r\n " +
" <WindowTopX>0</WindowTopX>\r\n " +
" <WindowTopY>0</WindowTopY>\r\n " +
" <RefModeR1C1/>\r\n " +
" <ProtectStructure>False</ProtectStructure>\r\n " +
" <ProtectWindows>False</ProtectWindows>\r\n " +
" </ExcelWorkbook>\r\n " +
"<Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat/>" +
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"dd/mm/yyyy;@\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
System.IO.StreamWriter excelDoc = null;
excelDoc = new System.IO.StreamWriter(fileName,false);
int sheetCount = 1;
excelDoc.Write(startExcelXML);
foreach (DataTable table in source.Tables)
{
int rowCount = 0;
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");
for (int x = 0; x < table.Columns.Count; x++)
{
excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
excelDoc.Write(table.Columns[x].ColumnName);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");
foreach (DataRow x in table.Rows)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 1048576)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //ID=" + rowCount + "
for (int y = 0; y < table.Columns.Count; y++)
{
System.Type rowType;
rowType = x[y].GetType();
switch (rowType.ToString())
{
case "System.String":
string XMLstring = x[y].ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace(">", ">");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
break;
case "System.DateTime":
//Excel has a specific Date Format of YYYY-MM-DD followed by
//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
//The Following Code puts the date stored in XMLDate
//to the format above
DateTime XMLDate = (DateTime)x[y];
string XMLDatetoString = ""; //Excel Converted Date
XMLDatetoString = XMLDate.Year.ToString() +
"-" +
(XMLDate.Month < 10 ? "0" +
XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
"-" +
(XMLDate.Day < 10 ? "0" +
XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
"T" +
(XMLDate.Hour < 10 ? "0" +
XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
":" +
(XMLDate.Minute < 10 ? "0" +
XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
":" +
(XMLDate.Second < 10 ? "0" +
XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
".000";
excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
"<Data ss:Type=\"DateTime\">");
excelDoc.Write(XMLDatetoString);
excelDoc.Write("</Data></Cell>");
break;
case "System.Boolean":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Decimal":
case "System.Double":
excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
"<Data ss:Type=\"Number\">");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.DBNull":
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
break;
default:
throw (new Exception(rowType.ToString() + " not handled."));
}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write("</Worksheet>");
sheetCount++;
}
const string endExcelOptions1 = "\r\n<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n" +
"<Selected/>\r\n" +
"<ProtectObjects>False</ProtectObjects>\r\n" +
"<ProtectScenarios>False</ProtectScenarios>\r\n" +
"</WorksheetOptions>\r\n";
excelDoc.Write(endExcelOptions1);
excelDoc.Write("</Workbook>");
excelDoc.Close();
}
我使用了几个选项:
如果XLSX是必须的:ExcelPackage是一个很好的开始,但当开发人员停止工作时就夭折了。ExML不是一个坏选项,我仍在一些生产网站上使用它。
不过,对于我的所有新项目,我都使用NPOI,即Apache POI的.NET端口。NPOI 2.0(Alpha)也支持XLSX。