简体   繁体   English

如何在不安装 Microsoft Office 的情况下在 C# 中创建 Excel(.XLS 和 .XLSX)文件?

[英]How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?如何使用 C# 创建 Excel 电子表格,而无需在运行代码的机器上安装 Excel?

You can use a library called ExcelLibrary.您可以使用名为 ExcelLibrary 的库。 It's a free, open source library posted on Google Code:这是一个发布在 Google Code 上的免费开源库:

ExcelLibrary Excel库

This looks to be a port of the PHP ExcelWriter that you mentioned above.这看起来是你上面提到的 PHP ExcelWriter 的一个端口。 It will not write to the new .xlsx format yet, but they are working on adding that functionality in.它还不会写入新的 .xlsx 格式,但他们正在努力添加该功能。

It's very simple, small and easy to use.它非常简单、小巧且易于使用。 Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.此外,它还有一个 DataSetHelper,可让您使用 DataSets 和 DataTables 轻松处理 Excel 数据。

ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. ExcelLibrary 似乎仍然只适用于较旧的 Excel 格式(.xls 文件),但将来可能会增加对较新的 2007/2010 格式的支持。

You can also use EPPlus , which works only for Excel 2007/2010 format files (.xlsx files).您还可以使用EPPlus ,它仅适用于 Excel 2007/2010 格式文件(.xlsx 文件)。 There's also NPOI which works with both.还有NPOI可以同时使用。

There are a few known bugs with each library as noted in the comments.如评论中所述,每个库都有一些已知的错误。 In all, EPPlus seems to be the best choice as time goes on.总而言之,随着时间的推移,EPPlus 似乎是最好的选择。 It seems to be more actively updated and documented as well.它似乎也更积极地更新和记录。

Also, as noted by @АртёмЦарионов below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support ( Pivot table issue in ExcelLibrary )此外,正如下面@АртёмЦарионов 所指出的,EPPlus 支持数据透视表,而 ExcelLibrary 可能有一些支持( ExcelLibrary 中的数据透视表问题

Here are a couple links for quick reference:这里有几个链接供快速参考:
ExcelLibrary - GNU Lesser GPL ExcelLibrary - GNU 小 GPL
EPPlus - GNU (LGPL) - No longer maintained EPPlus - GNU (LGPL) - 不再维护
EPPlus 5 - Polyform Noncommercial - Starting May 2020 EPPlus 5 - Polyform Noncommercial - 从 2020 年 5 月开始
NPOI - Apache License NPOI - Apache 许可证

Here some example code for ExcelLibrary:这里有一些 ExcelLibrary 的示例代码:

Here is an example taking data from a database and creating a workbook from it.这是从数据库中获取数据并从中创建工作簿的示例。 Note that the ExcelLibrary code is the single line at the bottom:请注意 ExcelLibrary 代码是底部的单行:

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Creating the Excel file is as easy as that.创建 Excel 文件就是这么简单。 You can also manually create Excel files, but the above functionality is what really impressed me.您也可以手动创建 Excel 文件,但上述功能给我留下了深刻的印象。

If you are happy with the xlsx format, try my GitHub project, EPPlus .如果您对 xlsx 格式感到满意,请尝试我的 GitHub 项目EPPlus It started with the source from ExcelPackage, but today it's a total rewrite.它从 ExcelPackage 的源开始,但今天完全重写。 It supports ranges, cell styling, charts, shapes, pictures, named ranges, AutoFilter and a lot of other stuff.它支持范围、单元格样式、图表、形状、图片、命名范围、自动筛选和许多其他内容。

And what about using Open XML SDK 2.0 for Microsoft Office?将 Open XML SDK 2.0 用于 Microsoft Office 怎么样?

A few benefits:几个好处:

  • Doesn't require Office installed不需要安装 Office
  • Made by Microsoft = decent MSDN documentation由微软制造 = 体面的 MSDN 文档
  • Just one .Net dll to use in project只需一个 .Net dll 即可在项目中使用
  • SDK comes with many tools like diff, validator, etc SDK 附带了许多工具,如 diff、验证器等

Links:链接:

I've used with success the following open source projects:我成功地使用了以下开源项目:

  • ExcelPackage for OOXML formats (Office 2007) OOXML 格式的 ExcelPackage (Office 2007)

  • NPOI for .XLS format (Office 2003). .XLS 格式的 NPOI (Office 2003)。 NPOI 2.0 (Beta) also supports XLSX. NPOI 2.0 (Beta) 也支持 XLSX。

Take a look at my blog posts:看看我的博文:

Creating Excel spreadsheets .XLS and .XLSX in C# 在 C# 中创建 Excel 电子表格 .XLS 和 .XLSX

NPOI with Excel Table and dynamic Chart 带有 Excel 表格和动态图表的 NPOI

You can use OLEDB to create and manipulate Excel files.您可以使用 OLEDB 来创建和操作 Excel 文件。 Check this: Reading and Writing Excel using OLEDB .检查这个: 使用 OLEDB 读取和写入 Excel

Typical example:典型例子:

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();
}

EDIT - Some more links:编辑 - 更多链接:

The commercial solution, SpreadsheetGear for .NET will do it.用于.NET的商业解决方案SpreadsheetGear可以做到这一点。

You can see live ASP.NET (C# and VB) samples here and download an evaluation version here .你可以看到现场ASP.NET(C#和VB)样本这里下载一个评估版本在这里

Disclaimer: I own SpreadsheetGear LLC免责声明:我拥有 SpreadsheetGear LLC

A few options I have used:我使用过的几个选项:

If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it.如果 XLSX 是必须的: ExcelPackage是一个好的开始,但在开发人员停止工作时就消失了。 ExML picked up from there and added a few features. ExML 从那里开始学习并添加了一些功能。 ExML isn't a bad option, I'm still using it in a couple of production websites. ExML不是一个糟糕的选择,我仍在几个生产网站中使用它。

For all of my new projects, though, I'm using NPOI , the .NET port of Apache POI .不过,对于我所有的新项目,我都使用NPOIApache POI的 .NET 端口。 NPOI 2.0 (Alpha) also supports XLSX. NPOI 2.0 (Alpha)也支持 XLSX。

An extremely lightweight option may be to use HTML tables.一个非常轻量级的选择可能是使用 HTML 表格。 Just create head, body, and table tags in a file, and save it as a file with an .xls extension.只需在文件中创建 head、body 和 table 标签,并将其保存为扩展名为 .xls 的文件。 There are Microsoft specific attributes that you can use to style the output, including formulas.您可以使用 Microsoft 特定的属性来设置输出的样式,包括公式。

I realize that you may not be coding this in a web application, but here is an example of the composition of an Excel file via an HTML table.我意识到您可能不会在 Web 应用程序中对此进行编码,但这里是通过 HTML 表组合 Excel 文件的示例 This technique could be used if you were coding a console app, desktop app, or service.如果您正在编写控制台应用程序、桌面应用程序或服务,则可以使用此技术。

If you're creating Excel 2007/2010 files give this open source project a try: https://github.com/closedxml/closedxml如果您正在创建 Excel 2007/2010 文件,请尝试使用此开源项目: https : //github.com/closedxml/closedxml

It provides an object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents.它提供了一种面向对象的方式来操作文件(类似于 VBA),而无需处理 XML 文档的麻烦。 It can be used by any .NET language like C# and Visual Basic (VB).它可以被任何 .NET 语言使用,如 C# 和 Visual Basic (VB)。

ClosedXML allows you to create Excel 2007/2010 files without the Excel application. ClosedXML 允许您在没有 Excel 应用程序的情况下创建 Excel 2007/2010 文件。 The typical example is creating Excel reports on a web server:典型示例是在 Web 服务器上创建 Excel 报告:

 var workbook = new XLWorkbook(); var worksheet = workbook.Worksheets.Add("Sample Sheet"); worksheet.Cell("A1").Value = "Hello World!"; workbook.SaveAs("HelloWorld.xlsx");

You actually might want to check out the interop classes available in C# (eg Microsoft.Office.Interop.Excel . You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the C# Documentation here (Interop for Excel starts on page 1072 of the C# PDF).您实际上可能想查看 C# 中可用的互操作类(例如Microsoft.Office.Interop.Excel 。您说没有 OLE(这不是),但互操作类非常易于使用。查看C# 文档此处(Interop for Excel 从 C# PDF 的第 1072 页开始)。

You might be impressed if you haven't tried them.如果你没有尝试过,你可能会印象深刻。

Please be warned of Microsoft's stance on this:请注意微软对此的立场

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. Microsoft 当前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)自动化 Microsoft Office 应用程序,因为 Office 可能表现出不稳定的行为和/或在此环境中运行 Office 时出现死锁。

You can use ExcelXmlWriter .您可以使用ExcelXmlWriter

It works fine.它工作正常。

Here's a completely free C# library, which lets you export from a DataSet , DataTable or List<> into a genuine Excel 2007 .xlsx file, using the OpenXML libraries:这是一个完全免费的 C# 库,它允许您使用 OpenXML 库从DataSetDataTableList<>导出到真正的 Excel 2007 .xlsx 文件中:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htmhttp://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

Full source code is provided - free of charge - along with instructions, and a demo application.提供完整的源代码 - 免费 - 连同说明和演示应用程序。

After adding this class to your application, you can export your DataSet to Excel in just one line of code:将此类添加到您的应用程序后,您只需一行代码即可将您的数据集导出到 Excel:

CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

It doesn't get much simpler than that...没有比这更简单的了...

And it doesn't even require Excel to be present on your server.它甚至不需要在您的服务器上安装 Excel。

You could consider creating your files using the XML Spreadsheet 2003 format.您可以考虑使用XML Spreadsheet 2003格式创建文件。 This is a simple XML format using a well documented schema .这是一种使用良好文档架构的简单 XML 格式。

You may want to take a look at GemBox.Spreadsheet .您可能想看看GemBox.Spreadsheet

They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs.他们有一个具有所有功能的免费版本,但如果符合您的需要,每张纸限制为 150 行,每个工作簿限制为 5 张。

I haven't had need to use it myself yet, but does look interesting.我还没有需要自己使用它,但看起来确实很有趣。

Syncfusion Essential XlsIO can do this. Syncfusion Essential XlsIO可以做到这一点。 It has no dependency on Microsoft office and also has specific support for different platforms.它不依赖于 Microsoft Office,并且对不同平台也有特定的支持。

Code sample:代码示例:

//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);

The whole suite of controls is available for free through the community license program if you qualify (less than 1 million USD in revenue).如果您符合条件(收入低于 100 万美元),则可以通过社区许可计划免费获得整套控件。 Note: I work for Syncfusion.注意:我为 Syncfusion 工作。

Well,好,

you can also use a third party library like Aspose .你也可以使用像Aspose这样的第三方库。

This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case.这个库的好处是它不需要在你的机器上安装 Excel,这在你的情况下是理想的。

The various Office 2003 XML libraries avaliable work pretty well for smaller excel files.对于较小的 excel 文件,各种可用的 Office 2003 XML 库都可以很好地工作。 However, I find the sheer size of a large workbook saved in the XML format to be a problem.但是,我发现以 XML 格式保存的大型工作簿的绝对大小是一个问题。 For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.例如,我使用的工作簿在新的(当然压缩得更紧密)XLSX 格式中是 40MB,变成了 360MB 的 XML 文件。

As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats.就我的研究而言,有两个商业软件包允许输出为较旧的二进制文件格式。 They are:他们是:

Neither are cheap (500USD and 800USD respectively, I think).两者都不便宜(我认为分别为 500 美元和 800 美元)。 but both work independant of Excel itself.但两者都独立于 Excel 本身工作。

What I would be curious about is the Excel output module for the likes of OpenOffice.org.我会好奇的是 OpenOffice.org 之类的 Excel 输出模块。 I wonder if they can be ported from Java to .Net.我想知道它们是否可以从 Java 移植到 .Net。

I have written a simple code to export dataset to excel without using excel object by using System.IO.StreamWriter.我编写了一个简单的代码,通过使用 System.IO.StreamWriter 将数据集导出到 excel 而不使用 excel 对象。

Below is the code which will read all tables from dataset and write them to sheets one by one.下面是从数据集中读取所有表并将它们一一写入工作表的代码。 I took help from this article .我从这篇文章中得到了帮助。

public static void exportToExcel(DataSet source, string fileName)
{
        const string endExcelXML = "</Workbook>";
        const string startExcelXML = "<xml version>\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 <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=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName);

        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 == 64000)
                {
                    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++;
        }


        excelDoc.Write(endExcelXML);
        excelDoc.Close();
    }

OpenXML is also a good alternative that helps avoid installing MS Excel on Server.The Open XML SDK 2.0 provided by Microsoft simplifies the task of manipulating Open XML packages and the underlying Open XML schema elements within a package. OpenXML 也是一个很好的替代方案,有助于避免在服务器上安装 MS Excel。Microsoft 提供的 Open XML SDK 2.0 简化了操作 Open XML 包和包内底层 Open XML 架构元素的任务。 The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages. Open XML 应用程序编程接口 (API) 封装了开发人员在 Open XML 包上执行的许多常见任务。

Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server看看这个OpenXML:有助于避免在服务器上安装 MS Excel 的替代方案

I've just recently used FlexCel.NET and found it to be an excellent library!我最近刚使用FlexCel.NET ,发现它是一个出色的库! I don't say that about too many software products.我不是说太多的软件产品。 No point in giving the whole sales pitch here, you can read all the features on their website.在这里提供整个销售宣传毫无意义,您可以阅读他们网站上的所有功能。

It is a commercial product, but you get the full source if you buy it.它是一种商业产品,但如果您购买它,您将获得完整的资源。 So I suppose you could compile it into your assembly if you really wanted to.所以我想如果你真的想的话,你可以把它编译到你的程序集中。 Otherwise it's just one extra assembly to xcopy - no configuration or installation or anything like that.否则它只是 xcopy 的一个额外程序集 - 没有配置或安装或类似的东西。

I don't think you'll find any way to do this without third-party libraries as .NET framework, obviously, does not have built in support for it and OLE Automation is just a whole world of pain.我认为如果没有第三方库,您将找不到任何方法来做到这一点,因为 .NET 框架显然没有内置支持,OLE 自动化只是一个痛苦的世界。

我同意生成 XML 电子表格,这里有一个关于如何为 C# 3 做的例子(每个人都只是在 VB 9 中写博客:P) http://www.aaron-powell.com/linq-to-xml-to-擅长

Just want to add another reference to a third party solution that directly addresses your issue: http://www.officewriter.com只想添加对直接解决您的问题的第三方解决方案的另一个引用: http : //www.officewriter.com

(Disclaimer: I work for SoftArtisans, the company that makes OfficeWriter) (免责声明:我为制作 OfficeWriter 的公司 SoftArtisans 工作)

IKVM + POI IKVM + POI

Or, you could use the Interop ...或者,您可以使用互操作...

Here's a way to do it with LINQ to XML, complete with sample code:这是一种使用 LINQ to XML 完成此操作的方法,并附有示例代码:

Quickly Import and Export Excel Data with LINQ to XML 使用 LINQ to XML 快速导入和导出 Excel 数据

It's a little complex, since you have to import namespaces and so forth, but it does let you avoid any external dependencies.这有点复杂,因为您必须导入命名空间等,但它确实可以让您避免任何外部依赖项。

(Also, of course, it's VB .NET, not C#, but you can always isolate the VB .NET stuff in its own project to use XML Literals, and do everything else in C#.) (当然,它是 VB .NET,而不是 C#,但您始终可以在自己的项目中隔离 VB .NET 内容以使用 XML 文字,并在 C# 中执行其他所有操作。)

The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool.从 C# 创建 Excel 文件的最简单、最快的方法是使用 Open XML Productivity Tool。 The Open XML Productivity Tool comes with the Open XML SDK installation. Open XML Productivity Tool 随 Open XML SDK 安装一起提供。 The tool reverse engineers any Excel file into C# code.该工具将任何 Excel 文件反向工程为 C# 代码。 The C# code can then be used to re-generate that file.然后可以使用 C# 代码重新生成该文件。

An overview of the process involved is:所涉及的过程概述如下:

  1. Install the Open XML SDK with the tool.使用该工具安装 Open XML SDK。
  2. Create an Excel file using the latest Excel client with desired look.使用具有所需外观的最新 Excel 客户端创建 Excel 文件。 Name it DesiredLook.xlsx .将其命名为DesiredLook.xlsx
  3. With the tool open DesiredLook.xlsx and click the Reflect Code button near the top.使用该工具打开DesiredLook.xlsx并单击顶部附近的 Reflect Code 按钮。 在此处输入图片说明
  4. The C# code for your file will be generated in the right pane of the tool.文件的 C# 代码将在工具的右侧窗格中生成。 Add this to your C# solution and generate files with that desired look.将此添加到您的 C# 解决方案并生成具有所需外观的文件。

As a bonus, this method works for any Word and PowerPoint files.作为奖励,此方法适用于任何 Word 和 PowerPoint 文件。 As the C# developer, you will then make changes to the code to fit your needs.作为 C# 开发人员,您随后将对代码进行更改以满足您的需要。

I have developed a simple WPF app on github which will run on Windows for this purpose.为此,我 在 github 上开发了一个 简单的 WPF 应用程序,它将在 Windows 运行。 There is a placeholder class called GeneratedClass where you can paste the generated code.有一个名为GeneratedClass的占位符类,您可以在其中粘贴生成的代码。 If you go back one version of the file, it will generate an excel file like this:如果您返回该文件的一个版本,它将生成一个如下所示的 excel 文件:

在此处输入图片说明

You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation您可以使用此库创建格式良好的 Excel 文件: http : //officehelper.codeplex.com/documentation
See below sample:请参阅以下示例:

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");
}        

where sample look like this:示例如下所示:

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};
    }
}

Some 3rd party component vendors like Infragistics or Syncfusion provide very good Excel export capabilities that do not require Microsoft Excel to be installed. Infragistics 或 Syncfusion 等一些 3rd 方组件供应商提供了非常好的 Excel 导出功能,不需要安装 Microsoft Excel。

Since these vendors also provide advanced UI grid components, these components are particularly handy if you want the style and layout of an excel export to mimic the current state of a grid in the user interface of your application.由于这些供应商还提供高级 UI 网格组件,如果您希望 excel 导出的样式和布局在应用程序的用户界面中模拟网格的当前状态,这些组件将特别方便。

If your export is intended to be executed server side with emphasis on the data to be exported and with no link to the UI, then I would go for one of the free open source options (eg ExcelLibrary).如果您的导出打算在服务器端执行,重点是要导出的数据并且没有指向 UI 的链接,那么我会选择免费的开源选项之一(例如 ExcelLibrary)。

I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite.我以前参与过尝试在 Microsoft Office 套件上使用服务器端自动化的项目。 Based on this experience I would strongly recommend against that approach.基于这种经验,我强烈建议不要采用这种方法。

public class GridViewExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

Hi this solution is to export your grid view to your excel file it might help you out嗨,这个解决方案是将您的网格视图导出到您的 Excel 文件中,它可能对您有所帮助

Some useful Excel automation in C# , u can find from the following link. C# 中一些有用的 Excel 自动化,您可以从以下链接中找到。

http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm

bolton.博尔顿。

Look at samples how to create Excel files.查看示例如何创建 Excel 文件。

There are examples in C# and VB.NETC#VB.NET 中有示例

It manages XSL XSLX and CSV Excel files.它管理 XSL XSLX 和 CSV Excel 文件。

http://www.devtriogroup.com/ExcelJetcell/Samples http://www.devtriogroup.com/ExcelJetcell/Samples

The Java open source solution is Apache POI . Java 开源解决方案是Apache POI Maybe there is a way to setup interop here, but I don't know enough about Java to answer that.也许有一种方法可以在这里设置互操作,但我对 Java 的了解不够,无法回答这个问题。

When I explored this problem I ended up using the Interop assemblies.当我探索这个问题时,我最终使用了 Interop 程序集。

Have you ever tried sylk?你试过 sylk 吗?

We used to generate excelsheets in classic asp as sylk and right now we're searching for an excelgenerater too.我们曾经在经典 asp 中生成 excelsheets 作为 sylk,现在我们也在寻找一个 excelgenerator。

The advantages for sylk are, you can format the cells. sylk 的优点是,您可以格式化单元格。

You can just write it out to XML using the Excel XML format and name it with .XLS extension and it will open with excel.您可以使用 Excel XML 格式将其写成 XML,并使用 .XLS 扩展名命名,它将以 excel 打开。 You can control all the formatting (bold, widths, etc) in your XML file heading.您可以控制 XML 文件标题中的所有格式(粗体、宽度等)。

There is an example XML from Wikipedia .有一个来自 Wikipedia示例 XML

I also vote for GemBox.Spreadsheet .我也投票给GemBox.Spreadsheet

Very fast and easy to use, with tons of examples on their site.非常快速且易于使用,其网站上有大量示例。

Took my reporting tasks on a whole new level of execution speed.将我的报告任务提升到一个全新的执行速度水平。

One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting and export it to excel format.一个经常被忽视的非常简单的选项是使用Microsoft Reporting创建一个 .rdlc 报告并将其导出为 excel 格式。 You can design it in visual studio and generate the file using:您可以在 Visual Studio 中设计它并使用以下方法生成文件:

localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);

You can also export it do .doc or .pdf, using "WORDOPENXML" and "PDF" respectively, and it's supported on many different platforms such as ASP.NET and SSRS.您还可以将其导出为 .doc 或 .pdf,分别使用"WORDOPENXML""PDF" ,并且它在许多不同的平台上都受支持,例如 ASP.NET 和 SSRS。

It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.在可以查看结果的可视化设计器中进行更改要容易得多,相信我,一旦您开始对数据进行分组、格式化组标题、添加新部分,您就不会想弄乱数十个 XML 节点。

You can try my SwiftExcel library.你可以试试我的SwiftExcel库。 This library writes directly to the file, so it is very efficient.这个库直接写入文件,所以效率很高。 For example you can write 100k rows in few seconds without any memory usage.例如,您可以在几秒钟内写入 100k 行而无需任何内存使用。

Here is a simple example of usage:下面是一个简单的用法示例:

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    for (var row = 1; row <= 10; row++)
    {
        for (var col = 1; col <= 5; col++)
        {
            ew.Write($"row:{row}-col:{col}", col, row);
        }
    }
}

http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= why not just use the built in power of windows, just install office on the server, any application that you install can be automated. http://www.codeproject.com/KB/cs/Excel_and_C_.aspx <= 为什么不直接使用 Windows 的内置功能,只需在服务器上安装 office,您安装的任何应用程序都可以自动化。

So much easier just use the native methods.只需使用本机方法就容易多了。

If it installed you can use it, this is the most awesome and under used feature in windows it was Dubbed COM back in the good old days, and it saves you tons of time and pain.如果安装了它,您就可以使用它,这是 Windows 中最棒但未使用的功能,它在过去被称为 COM,它为您节省了大量时间和痛苦。

Or even easier just use the ref lib MS supplies - http://csharp.net-informations.com/excel/csharp-create-excel.htm或者更简单,只需使用 ref lib MS 用品 - http://csharp.net-informations.com/excel/csharp-create-excel.htm

How to create an Excel (.xslx) file using C# on OneDrive without installing Microsoft Office如何在不安装 Microsoft Office 的情况下在 OneDrive 上使用 C# 创建 Excel (.xslx) 文件

The Microsoft Graph API provides File and Excel APIs for creating and modifying Excel files stored in OneDrive for both enterprise and consumer accounts. Microsoft Graph API提供文件和 Excel API,用于为企业和消费者帐户创建和修改存储在 OneDrive 中的 Excel 文件。 The Microsoft.Graph NuGet package provides many interfaces for working with the File and Excel APIs. 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);
}

At this point, you now have an Excel file created in the user (enterprise or consumer) or group's OneDrive.此时,您现在已经在用户(企业或消费者)或组的 OneDrive 中创建了一个 Excel 文件。 You can now use the Excel APIs to make changes to the Excel file without using Excel and without needing to understand the Excel XML format .您现在可以使用Excel API更改 Excel 文件,而无需使用 Excel,也无需了解 Excel XML 格式

You can install OpenXml nuget package on Visual Studio.您可以在 Visual Studio 上安装 OpenXml nuget 包。 Here is a bit of code to export a data table to an excel file:这是将数据表导出到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

I recode again the code and now you can create an .xls file, later you can convert to Excel 2003 Open XML Format.我再次重新编码代码,现在您可以创建一个 .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();
    }

If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer.如果您从代码制作数据表或数据网格视图,您可以使用这种简单的方法保存所有数据。不推荐使用这种方法,但即使您没有在计算机中安装 MS Excel,它也能 100% 工作。

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!");
   }

Some time ago, I created a DLL on top of NPOI.前段时间,我在 NPOI 之上创建了一个 DLL。 It's very simple to use it:使用它非常简单:

IList<DummyPerson> dummyPeople = new List<DummyPerson>();
//Add data to dummyPeople...
IExportEngine engine = new ExcelExportEngine();
engine.AddData(dummyPeople); 
MemoryStream memory = engine.Export();

You could read more about it on here .您可以在此处阅读更多相关信息。

By the way, is 100% open source.顺便说一下,是 100% 开源的。 Feel free to use, edit and share ;)随意使用、编辑和分享;)

To save xls into xlsx format, we just need to call SaveAs method from Microsoft.Office.Interop.Excel library.要将 xls 保存为 xlsx 格式,我们只需要从Microsoft.Office.Interop.Excel库中调用SaveAs方法。 This method will take around 16 parameters and one of them is file format as well.此方法将需要大约 16 个参数,其中之一也是文件格式。

Microsoft document: Here SaveAs Method Arguments Microsoft 文档:此处为SaveAs 方法参数

The object we need to pass is like我们需要传递的对象就像

wb.SaveAs(filename, 51, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, false, false, 1,1, true, 
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)

Here, 51 is is enumeration value for XLSX这里,51 是 XLSX 的枚举值

For SaveAs in different file formats you can refer the xlFileFormat对于不同文件格式的另存为,您可以参考xlFileFormat

I wonder why nobody suggested PowerShell with the free ImportExcel Module;我想知道为什么没有人建议使用免费的 ImportExcel 模块使用 PowerShell; it creates XML-Excel files (xlsx) with ease.它可以轻松创建 XML-Excel 文件 (xlsx)。

Especially easy when creating Excel-sheets coming from Databases like SQL Server...创建来自 SQL Server 等数据库的 Excel 工作表时尤其容易...

In my projects, I use some several .net libraries to extract Excel File (both .xls and .xlsx)在我的项目中,我使用了一些 .net 库来提取 Excel 文件(.xls 和 .xlsx)

To Export data, I frequently use rdlc .为了导出数据,我经常使用rdlc

To modify excel files I use (Sample code when I try to set blank Cell A15):要修改我使用的 excel 文件(尝试设置空白单元格 A15 时的示例代码):

ClosedXML封闭的XML

        //Closed XML
        var workbook = new XLWorkbook(sUrlFile); // load the existing excel file
        var worksheet = workbook.Worksheets.Worksheet(1);
        worksheet.Cell("A15").SetValue("");
        workbook.Save();

IronXL IronXL

       string sUrlFile = "G:\\ReportAmortizedDetail.xls";
        WorkBook workbook = WorkBook.Load(sUrlFile);
        WorkSheet sheet = workbook.WorkSheets.First();
        //Select cells easily in Excel notation and return the calculated value
        sheet["A15"].First().Value = "";
        sheet["A15"].First().FormatString = "";

        workbook.Save();
        workbook.Close();
        workbook = null;

SpireXLS (When I try, the library print additional sheet to give information that we use the trial library SpireXLS (当我尝试时,图书馆打印附加表以提供我们使用试用图书馆的信息

            string sUrlFile = "G:\\ReportAmortizedDetail.xls";
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sUrlFile);
            //Get the 1st sheet
            Worksheet sheet = workbook.Worksheets[0];
            //Specify the cell range
            CellRange range = sheet.Range["A15"];
            //Find all matched text in the range
            CellRange[] cells = range.FindAllString("hi", false, false);
            //Replace text
            foreach (CellRange cell in range)
            {
                cell.Text = "";
            }
            //Save
            workbook.Save();

Jet Oledb杰特·奥尔德布

    //ExcelTool Class
    public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)
    {
        int iResult = -99;
        String sConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO'";
        OleDbConnection objConn = new OleDbConnection(sConnectionString);
        objConn.Open();
        OleDbCommand objCmdSelect = new OleDbCommand("UPDATE [" + sWorksheetName + "$" + sCellLocation + "] SET F1=" + UtilityClass.ValueSQL(sValue), objConn);
        objCmdSelect.ExecuteNonQuery();
        objConn.Close();

        return iResult;
    }

Usage :用法 :

    ExcelTool.ExcelUpdateSheets(sUrlFile, "ReportAmortizedDetail", "A15:A15", "");

Aspose Aspose

            var workbook = new Aspose.Cells.Workbook(sUrlFile);
            // access first (default) worksheet
            var sheet = workbook.Worksheets[0];
            // access CellsCollection of first worksheet
            var cells = sheet.Cells;
            // write HelloWorld to cells A1
            cells["A15"].Value = "";
            // save spreadsheet to disc
            workbook.Save(sUrlFile);
            workbook.Dispose();
            workbook = null;

I found another library that does it without much dependencies: MiniExcel .我找到了另一个没有太多依赖的库: MiniExcel

You can create a DataSet with DataTable s as spreadsheets (the name of the table being the name of the spreadsheet) and save it to .xlsx file by您可以使用DataTable创建一个DataSet作为电子表格(表的名称是电子表格的名称)并将其保存到.xlsx文件中

using var stream = File.Create(filePath);
stream.SaveAs(dataSet);

or或者

MiniExcel.SaveAs(filePath, dataSet);

It offers also reading of Excel files and does support reading and writing of CSV files.它还提供读取 Excel 个文件,并支持读取和写入 CSV 个文件。

Here is the simplest way to create an Excel file.这是创建 Excel 文件的最简单方法。

Excel files with extension .xlsx are compressed folders containing .XML files - but complicated.扩展名为 .xlsx 的 Excel 文件是包含 .XML 文件的压缩文件夹 - 但很复杂。

First create the folder structure as follows -首先创建文件夹结构如下 -

public class CreateFileOrFolder
{
    static void Main()
    {
        //
        // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder
        //
        // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
        //
        // .NET Framework 4.7.2
        //
        // Specify a name for your top-level folder.
        string folderName = @"C:\Users\david\Desktop\Book3";

        // To create a string that specifies the path to a subfolder under your
        // top-level folder, add a name for the subfolder to folderName.

        string pathString = System.IO.Path.Combine(folderName, "_rels");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "docProps");
        System.IO.Directory.CreateDirectory(pathString);
        pathString = System.IO.Path.Combine(folderName, "xl");
        System.IO.Directory.CreateDirectory(pathString);

        string subPathString = System.IO.Path.Combine(pathString, "_rels");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "theme");
        System.IO.Directory.CreateDirectory(subPathString);
        subPathString = System.IO.Path.Combine(pathString, "worksheets");
        System.IO.Directory.CreateDirectory(subPathString);
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

Next, create text files to hold the XML needed to describe the Excel spreadsheet.接下来,创建文本文件来保存描述 Excel 电子表格所需的 XML。

namespace MakeFiles3
{
    class Program
    {
        static void Main(string[] args)
        {
            //
            // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file
            //
            // .NET Framework 4.7.2
            //
            string fileName = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            fnWriteFile(fileName);
            fileName = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            fnWriteFile(fileName);
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool fnWriteFile(string strFilePath)
            {
                if (!System.IO.File.Exists(strFilePath))
                {
                    using (System.IO.FileStream fs = System.IO.File.Create(strFilePath))
                    {
                        return true;
                    }
                }
                else
                {
                    System.Console.WriteLine("File \"{0}\" already exists.", strFilePath);
                    return false;
                }
            }
        }
    }
}

Next populate the text files with XML.接下来用 XML 填充文本文件。

The XML required is fairly verbose so you may need to use this github repository.所需的 XML 相当冗长,因此您可能需要使用此 github 存储库。

https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs https://github.com/DaveTallett26/MakeFiles4/blob/master/MakeFiles4/Program.cs

//
// https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file
// .NET Framework 4.7.2
//
using System.IO;

namespace MakeFiles4
{
    class Program
    {
        static void Main(string[] args)
        {
            string xContents = @"a";
            string xFilename = @"a";
            xFilename = @"C:\Users\david\Desktop\Book3\[Content_Types].xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""><Default Extension=""rels"" ContentType=""application/vnd.openxmlformats-package.relationships+xml""/><Default Extension=""xml"" ContentType=""application/xml""/><Override PartName=""/xl/workbook.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml""/><Override PartName=""/xl/worksheets/sheet1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml""/><Override PartName=""/xl/theme/theme1.xml"" ContentType=""application/vnd.openxmlformats-officedocument.theme+xml""/><Override PartName=""/xl/styles.xml"" ContentType=""application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml""/><Override PartName=""/docProps/core.xml"" ContentType=""application/vnd.openxmlformats-package.core-properties+xml""/><Override PartName=""/docProps/app.xml"" ContentType=""application/vnd.openxmlformats-officedocument.extended-properties+xml""/></Types>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\_rels\.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"" Target=""docProps/app.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"" Target=""docProps/core.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"" Target=""xl/workbook.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\app.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Properties xmlns=""http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"" xmlns:vt=""http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes""><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=""2"" baseType=""variant""><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=""1"" baseType=""lpstr""><vt:lpstr>Sheet1</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0300</AppVersion></Properties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\docProps\core.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><cp:coreProperties xmlns:cp=""http://schemas.openxmlformats.org/package/2006/metadata/core-properties"" xmlns:dc=""http://purl.org/dc/elements/1.1/"" xmlns:dcterms=""http://purl.org/dc/terms/"" xmlns:dcmitype=""http://purl.org/dc/dcmitype/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><dc:creator>David Tallett</dc:creator><cp:lastModifiedBy>David Tallett</cp:lastModifiedBy><dcterms:created xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:15Z</dcterms:created><dcterms:modified xsi:type=""dcterms:W3CDTF"">2021-10-26T15:47:35Z</dcterms:modified></cp:coreProperties>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\styles.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><styleSheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac x16r2 xr"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:x16r2=""http://schemas.microsoft.com/office/spreadsheetml/2015/02/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision""><fonts count=""1"" x14ac:knownFonts=""1""><font><sz val=""11""/><color theme=""1""/><name val=""Calibri""/><family val=""2""/><scheme val=""minor""/></font></fonts><fills count=""2""><fill><patternFill patternType=""none""/></fill><fill><patternFill patternType=""gray125""/></fill></fills><borders count=""1""><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0""/></cellStyleXfs><cellXfs count=""1""><xf numFmtId=""0"" fontId=""0"" fillId=""0"" borderId=""0"" xfId=""0""/></cellXfs><cellStyles count=""1""><cellStyle name=""Normal"" xfId=""0"" builtinId=""0""/></cellStyles><dxfs count=""0""/><tableStyles count=""0"" defaultTableStyle=""TableStyleMedium2"" defaultPivotStyle=""PivotStyleLight16""/><extLst><ext uri=""{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"" xmlns:x14=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/main""><x14:slicerStyles defaultSlicerStyle=""SlicerStyleLight1""/></ext><ext uri=""{9260A510-F301-46a8-8635-F512D64BE5F5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:timelineStyles defaultTimelineStyle=""TimeSlicerStyleLight1""/></ext></extLst></styleSheet>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\workbook.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x15 xr xr6 xr10 xr2"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr6=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision6"" xmlns:xr10=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision10"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2""><fileVersion appName=""xl"" lastEdited=""7"" lowestEdited=""7"" rupBuild=""24430""/><workbookPr defaultThemeVersion=""166925""/><mc:AlternateContent xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""><mc:Choice Requires=""x15""><x15ac:absPath url=""C:\Users\david\Desktop\"" xmlns:x15ac=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac""/></mc:Choice></mc:AlternateContent><xr:revisionPtr revIDLastSave=""0"" documentId=""8_{C633700D-2D40-49EE-8C5E-2561E28A6758}"" xr6:coauthVersionLast=""47"" xr6:coauthVersionMax=""47"" xr10:uidLastSave=""{00000000-0000-0000-0000-000000000000}""/><bookViews><workbookView xWindow=""-120"" yWindow=""-120"" windowWidth=""29040"" windowHeight=""15840"" xr2:uid=""{934C5B62-1DC1-4322-BAE8-00D615BD2FB3}""/></bookViews><sheets><sheet name=""Sheet1"" sheetId=""1"" r:id=""rId1""/></sheets><calcPr calcId=""191029""/><extLst><ext uri=""{140A7094-0E35-4892-8432-C4D2E57EDEB5}"" xmlns:x15=""http://schemas.microsoft.com/office/spreadsheetml/2010/11/main""><x15:workbookPr chartTrackingRefBase=""1""/></ext><ext uri=""{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}"" xmlns:xcalcf=""http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures""><xcalcf:calcFeatures><xcalcf:feature name=""microsoft.com:RD""/><xcalcf:feature name=""microsoft.com:Single""/><xcalcf:feature name=""microsoft.com:FV""/><xcalcf:feature name=""microsoft.com:CNMTM""/><xcalcf:feature name=""microsoft.com:LET_WF""/></xcalcf:calcFeatures></ext></extLst></workbook>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\_rels\workbook.xml.rels";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><Relationships xmlns=""http://schemas.openxmlformats.org/package/2006/relationships""><Relationship Id=""rId3"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"" Target=""styles.xml""/><Relationship Id=""rId2"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"" Target=""theme/theme1.xml""/><Relationship Id=""rId1"" Type=""http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"" Target=""worksheets/sheet1.xml""/></Relationships>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\theme\theme1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><a:theme xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" name=""Office Theme""><a:themeElements><a:clrScheme name=""Office""><a:dk1><a:sysClr val=""windowText"" lastClr=""000000""/></a:dk1><a:lt1><a:sysClr val=""window"" lastClr=""FFFFFF""/></a:lt1><a:dk2><a:srgbClr val=""44546A""/></a:dk2><a:lt2><a:srgbClr val=""E7E6E6""/></a:lt2><a:accent1><a:srgbClr val=""4472C4""/></a:accent1><a:accent2><a:srgbClr val=""ED7D31""/></a:accent2><a:accent3><a:srgbClr val=""A5A5A5""/></a:accent3><a:accent4><a:srgbClr val=""FFC000""/></a:accent4><a:accent5><a:srgbClr val=""5B9BD5""/></a:accent5><a:accent6><a:srgbClr val=""70AD47""/></a:accent6><a:hlink><a:srgbClr val=""0563C1""/></a:hlink><a:folHlink><a:srgbClr val=""954F72""/></a:folHlink></a:clrScheme><a:fontScheme name=""Office""><a:majorFont><a:latin typeface=""Calibri Light"" panose=""020F0302020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック Light""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等线 Light""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Times New Roman""/><a:font script=""Hebr"" typeface=""Times New Roman""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""MoolBoran""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Times New Roman""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:majorFont><a:minorFont><a:latin typeface=""Calibri"" panose=""020F0502020204030204""/><a:ea typeface=""""/><a:cs typeface=""""/><a:font script=""Jpan"" typeface=""游ゴシック""/><a:font script=""Hang"" typeface=""맑은 고딕""/><a:font script=""Hans"" typeface=""等线""/><a:font script=""Hant"" typeface=""新細明體""/><a:font script=""Arab"" typeface=""Arial""/><a:font script=""Hebr"" typeface=""Arial""/><a:font script=""Thai"" typeface=""Tahoma""/><a:font script=""Ethi"" typeface=""Nyala""/><a:font script=""Beng"" typeface=""Vrinda""/><a:font script=""Gujr"" typeface=""Shruti""/><a:font script=""Khmr"" typeface=""DaunPenh""/><a:font script=""Knda"" typeface=""Tunga""/><a:font script=""Guru"" typeface=""Raavi""/><a:font script=""Cans"" typeface=""Euphemia""/><a:font script=""Cher"" typeface=""Plantagenet Cherokee""/><a:font script=""Yiii"" typeface=""Microsoft Yi Baiti""/><a:font script=""Tibt"" typeface=""Microsoft Himalaya""/><a:font script=""Thaa"" typeface=""MV Boli""/><a:font script=""Deva"" typeface=""Mangal""/><a:font script=""Telu"" typeface=""Gautami""/><a:font script=""Taml"" typeface=""Latha""/><a:font script=""Syrc"" typeface=""Estrangelo Edessa""/><a:font script=""Orya"" typeface=""Kalinga""/><a:font script=""Mlym"" typeface=""Kartika""/><a:font script=""Laoo"" typeface=""DokChampa""/><a:font script=""Sinh"" typeface=""Iskoola Pota""/><a:font script=""Mong"" typeface=""Mongolian Baiti""/><a:font script=""Viet"" typeface=""Arial""/><a:font script=""Uigh"" typeface=""Microsoft Uighur""/><a:font script=""Geor"" typeface=""Sylfaen""/><a:font script=""Armn"" typeface=""Arial""/><a:font script=""Bugi"" typeface=""Leelawadee UI""/><a:font script=""Bopo"" typeface=""Microsoft JhengHei""/><a:font script=""Java"" typeface=""Javanese Text""/><a:font script=""Lisu"" typeface=""Segoe UI""/><a:font script=""Mymr"" typeface=""Myanmar Text""/><a:font script=""Nkoo"" typeface=""Ebrima""/><a:font script=""Olck"" typeface=""Nirmala UI""/><a:font script=""Osma"" typeface=""Ebrima""/><a:font script=""Phag"" typeface=""Phagspa""/><a:font script=""Syrn"" typeface=""Estrangelo Edessa""/><a:font script=""Syrj"" typeface=""Estrangelo Edessa""/><a:font script=""Syre"" typeface=""Estrangelo Edessa""/><a:font script=""Sora"" typeface=""Nirmala UI""/><a:font script=""Tale"" typeface=""Microsoft Tai Le""/><a:font script=""Talu"" typeface=""Microsoft New Tai Lue""/><a:font script=""Tfng"" typeface=""Ebrima""/></a:minorFont></a:fontScheme><a:fmtScheme name=""Office""><a:fillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:lumMod val=""110000""/><a:satMod val=""105000""/><a:tint val=""67000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""103000""/><a:tint val=""73000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""105000""/><a:satMod val=""109000""/><a:tint val=""81000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:satMod val=""103000""/><a:lumMod val=""102000""/><a:tint val=""94000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:satMod val=""110000""/><a:lumMod val=""100000""/><a:shade val=""100000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:lumMod val=""99000""/><a:satMod val=""120000""/><a:shade val=""78000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=""6350"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""12700"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln><a:ln w=""19050"" cap=""flat"" cmpd=""sng"" algn=""ctr""><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:prstDash val=""solid""/><a:miter lim=""800000""/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=""57150"" dist=""19050"" dir=""5400000"" algn=""ctr"" rotWithShape=""0""><a:srgbClr val=""000000""><a:alpha val=""63000""/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=""phClr""/></a:solidFill><a:solidFill><a:schemeClr val=""phClr""><a:tint val=""95000""/><a:satMod val=""170000""/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=""1""><a:gsLst><a:gs pos=""0""><a:schemeClr val=""phClr""><a:tint val=""93000""/><a:satMod val=""150000""/><a:shade val=""98000""/><a:lumMod val=""102000""/></a:schemeClr></a:gs><a:gs pos=""50000""><a:schemeClr val=""phClr""><a:tint val=""98000""/><a:satMod val=""130000""/><a:shade val=""90000""/><a:lumMod val=""103000""/></a:schemeClr></a:gs><a:gs pos=""100000""><a:schemeClr val=""phClr""><a:shade val=""63000""/><a:satMod val=""120000""/></a:schemeClr></a:gs></a:gsLst><a:lin ang=""5400000"" scaled=""0""/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:extLst><a:ext uri=""{05A4C25C-085E-4340-85A3-A5531E510DB2}""><thm15:themeFamily xmlns:thm15=""http://schemas.microsoft.com/office/thememl/2012/main"" name=""Office Theme"" id=""{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}"" vid=""{4A3C46E8-61CC-4603-A589-7422A47A8E4A}""/></a:ext></a:extLst></a:theme>";
            StartExstream(xContents, xFilename);

            xFilename = @"C:\Users\david\Desktop\Book3\xl\worksheets\sheet1.xml";
            xContents = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"" mc:Ignorable=""x14ac xr xr2 xr3"" xmlns:x14ac=""http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"" xmlns:xr=""http://schemas.microsoft.com/office/spreadsheetml/2014/revision"" xmlns:xr2=""http://schemas.microsoft.com/office/spreadsheetml/2015/revision2"" xmlns:xr3=""http://schemas.microsoft.com/office/spreadsheetml/2016/revision3"" xr:uid=""{54E3D330-4E78-4755-89E0-1AADACAC4953}""><dimension ref=""A1:A3""/><sheetViews><sheetView tabSelected=""1"" workbookViewId=""0""><selection activeCell=""A4"" sqref=""A4""/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=""15"" x14ac:dyDescent=""0.25""/><sheetData><row r=""1"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A1""><v>1</v></c></row><row r=""2"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A2""><v>2</v></c></row><row r=""3"" spans=""1:1"" x14ac:dyDescent=""0.25""><c r=""A3""><v>3</v></c></row></sheetData><pageMargins left=""0.7"" right=""0.7"" top=""0.75"" bottom=""0.75"" header=""0.3"" footer=""0.3""/></worksheet>";
            StartExstream(xContents, xFilename);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();

            bool StartExstream(string strLine, string strFileName)
            {
                // Write the string to a file.
                using (StreamWriter outputFile = new StreamWriter(strFileName))
                {
                    outputFile.WriteLine(strLine);
                    return true;
                }
            }
        }
    }
}

Finally ZIP the folder structure containing the XML -最后压缩包含 XML 的文件夹结构 -

namespace ZipFolder
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string xlPath = @"C:\Users\david\Desktop\Book3.xlsx";
            string folderPath = @"C:\Users\david\Desktop\Book3";

            System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, xlPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

This produces an Excel file named Book3.xlsx which is valid and opens cleanly in Excel 365 on Windows 11.这会生成一个名为 Book3.xlsx 的 Excel 文件,该文件有效并在 Windows 11 上的 Excel 365 中干净地打开。

The result is a very simple Excel spreadsheet but you may need to reverse engineer a more complex version.结果是一个非常简单的 Excel 电子表格,但您可能需要对更复杂的版本进行逆向工程。 Here is the code to unzip a .xlsx file.这是解压缩 .xlsx 文件的代码。

namespace UnZipXL
// .NET Framework 4.7.2
// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top
{
    class Program
    {
        static void Main(string[] args)
        {
            string XLPath = @"C:\Users\david\Desktop\Book2.xlsx";
            string extractPath = @"C:\Users\david\Desktop\extract";

            System.IO.Compression.ZipFile.ExtractToDirectory(XLPath, extractPath);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

我会建议使用 Openxml 库,它是轻量级的,在处理 excel 时也减少了 ram 消耗,同时通过代码操作它。

check this out no need for third party libraries you can simply export datatable data to excel file using this检查一下不需要第三方库,您可以使用它简单地将数据表数据导出到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();

I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that exel cannot open the file bcz file might be coruupted or extension of the file is not compatible.我正在使用以下代码创建 excel 2007 文件,该文件创建文件并写入该文件,但是当我打开文件但它给我错误,exel 无法打开文件 bcz 文件可能已损坏或文件的扩展名不兼容。 but if i used .xls for file it work fines但如果我使用 .xls 作为文件,它可以正常工作

for (int i = 0; i < TotalFile; i++)
{
    Contact.Clear();
    if (innerloop == SplitSize)
    {
        for (int j = 0; j < SplitSize; j++)
        {
            string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
            Contact.Add(strContact);
        }
        string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
                         File.WriteAllLines(strExcel, Contact.ToArray());
    }
}

also refer link也参考链接

http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在未安装 Microsoft Office 的情况下使用 C# 将 .xls 文件转换为 .xlsx? - How to convert .xls file to .xlsx using C# and without Microsoft Office installed? C# - 将xls文件转换为没有office组件的xlsx - C# - convert xls file to xlsx without office components 将ibfs(从网站下载的Excel文件)文件转换为.xls / .xlsx文件格式,而无需使用C#Asp.net Web应用程序安装Office - Converting ibfs (Downloaded Excel files from websites) files to .xls/.xlsx file format without installing Office using C# Asp.net Web application 如何在C#中读取Excel(.XLS和.XLSX)文件? - How to read Excel (.XLS and .XLSX) file in C#? C# (Microsoft.Office.Interop.Excel),将数据另存为 Excel 2003 文件(xls) - C# (Microsoft.Office.Interop.Excel), Save Data as Excel 2003 File(xls) 如何使用C#将.xlsx文件转换为.xlsx,然后使用epplus编辑.xlsx文件,例如为单元格着色 - How do I convert .xls file to .xlsx using c# and then edit the .xlsx file like coloring cells using epplus 如何在不使用 Microsoft.Office.Interop.Excel 库的情况下在 C# 中读取 excel 文件 - How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries 如何使用密码保护创建Excel 2003(.XLS)文件,而不使用c#安装Excel? - How to create Excel 2003 (.XLS) file with password protection without Excel installed with c#? 在 C# 中使用 Microsoft.Office.Interop.Excel 创建新 Excel.Workbook 时的 ReportINI.xls 消息 - ReportINI.xls message when create new Excel.Workbook with Microsoft.Office.Interop.Excel in C# 如何使用C#创建和写入Excel .xls文件 - How to create and write Excel .xls file using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM