如何使用C#创建Excel电子表格而不需要在运行代码的计算机上安装Excel?
当前回答
我重新编码了代码,现在可以创建.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();
}
其他回答
一个经常被忽略的简单选项是使用Microsoft Reporting创建.rdlc报告并将其导出为excel格式。您可以在visual studio中设计它,并使用以下方法生成文件:
localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);
您还可以分别使用“WORDOPENXML”和“pdf”将其导出为.doc或.pdf,并且它在许多不同的平台(如ASP.NET和SSRS)上都受支持。
在可视化设计器中进行更改要容易得多,在那里您可以看到结果,相信我,一旦开始分组数据、格式化组标题、添加新节,您就不想处理几十个XML节点。
检查一下,不需要第三方库,您可以使用以下命令将数据表数据导出到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();
您只需使用Excel XML格式将其写入XML,并以.XLS扩展名命名,它将以Excel打开。您可以控制XML文件标题中的所有格式(粗体、宽度等)。
维基百科中有一个XML示例。
Java开源解决方案是Apache POI。也许这里有一种设置互操作的方法,但我对Java的了解不够,无法回答这个问题。
当我探索这个问题时,我最终使用了互操作程序集。
前段时间,我在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循环中编辑字典值