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

时间:2023-01-15 10:40:50

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?

41 个解决方案

#1


910  

You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:

您可以使用名为ExcelLibrary的库。这是一个免费的开源库,发布在Google Code上:

ExcelLibrary

This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.

这看起来是您上面提到的PHP ExcelWriter的一个端口。它还不会写入新的.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,可让您使用DataSet和DataTable轻松处理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 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. It seems to be more actively updated and documented as well.

如评论中所述,每个库都有一些已知的错误。总之,随着时间的推移,EPPlus似乎是最好的选择。它似乎也更积极地更新和记录。

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
EPPlus - GNU Lesser General Public License (LGPL)

这里有几个链接供快速参考:ExcelLibrary - GNU较小GPL EPPlus - GNU较宽松通用公共许可证(LGPL)

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. You can also manually create Excel files, but the above functionality is what really impressed me.

创建Excel文件就像这样简单。您也可以手动创建Excel文件,但上述功能给我留下了深刻的印象。

#2


512  

If you are happy with the xlsx format, try my codeplex GitHub project. EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff.

如果您对xlsx格式感到满意,请尝试我的codeplex GitHub项目。 EPPlus。从ExcelPackage的源代码开始,但今天它完全重写。支持范围,单元格样式,图表,形状,图片,名称范围,自动过滤器和许多其他东西。

#3


154  

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). NPOI 2.0 (Alpha) also supports XLSX.

    NPOI for .XLS格式(Office 2003)。 NPOI 2.0(Alpha)也支持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

NPOI与Excel表和动态图表

#4


148  

And what about using Open XML SDK 2.0 for Microsoft Office?

那么使用Open XML SDK 2.0 for Microsoft Office呢?

A few benefits:

一些好处:

  • Doesn't require Office installed
  • 不需要安装Office

  • Made by Microsoft = decent MSDN documentation
  • 由Microsoft制作=体面的MSDN文档

  • Just one .Net dll to use in project
  • 只需一个.Net dll即可在项目中使用

  • SDK comes with many tools like diff, validator, etc
  • SDK附带了许多工具,如diff,validator等

Links:

#5


98  

You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.

您可以使用OLEDB来创建和操作Excel文件。检查:使用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:

编辑 - 更多链接:

#6


75  

The commercial solution, SpreadsheetGear for .NET will do it.

商业解决方案,SpreadsheetGear for .NET将会这样做。

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

#7


59  

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. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.

如果XLSX是必须的:ExcelPackage是一个良好的开端,但在开发人员退出工作时就已经死了。 ExML从那里获得并添加了一些功能。 ExML不是一个糟糕的选择,我仍然在几个生产网站中使用它。

For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX.

但是,对于我的所有新项目,我使用的是NPOI,Apache POI的.NET端口。 NPOI 2.0(Alpha)也支持XLSX。

#8


57  

An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.

一个非常轻量级的选项可能是使用HTML表。只需在文件中创建head,body和table标签,并将其另存为扩展名为.xls的文件。您可以使用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. This technique could be used if you were coding a console app, desktop app, or service.

我意识到您可能没有在Web应用程序中对此进行编码,但这里是通过HTML表格组成Excel文件的示例。如果您正在编写控制台应用程序,桌面应用程序或服务,则可以使用此技术。

#9


44  

You can use ExcelXmlWriter.

您可以使用ExcelXmlWriter。

It works fine.

它工作正常。

#10


42  

You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use.

您实际上可能想要查看互操作类。你说没有OLE(这不是),但互操作类很容易使用。

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在此环境中运行时出现死锁或死锁。

#11


41  

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. It can be used by any .NET language like C# and Visual Basic (VB).

它提供了一种面向对象的方式来操作文件(类似于VBA),而无需处理XML文档的麻烦。它可以被任何.NET语言使用,如C#和Visual Basic(VB)。

ClosedXML allows you to create Excel 2007/2010 files without the Excel application. The typical example is creating Excel reports on a web server:

ClosedXML允许您在不使用Excel应用程序的情况下创建Excel 2007/2010文件。典型示例是在Web服务器上创建Excel报告:

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

#12


30  

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库从DataSet,DataTable或List <>导出到真正的Excel 2007 .xlsx文件中:

http://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:

将此类添加到应用程序后,只需一行代码就可以将DataSet导出到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出现在您的服务器上。

#13


23  

You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.

您可以考虑使用XML Spreadsheet 2003格式创建文件。这是一种使用记录良好的架构的简单XML格式。

#14


19  

Syncfusion Essential XlsIO can do this. It has no dependency on Microsoft office and also has specific support for different platforms.

Syncfusion Essential XlsIO可以做到这一点。它不依赖于Microsoft办公室,并且对不同平台也有特定支持。

  • ASP.NET
  • ASP.NET MVC
  • UWP
  • Xamarin
  • WPF and Windows Forms
  • WPF和Windows窗体

  • Windows Service and batch based operations
  • Windows服务和基于批处理的操作

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). Note: I work for Syncfusion.

如果您符合资格(收入不到100万美元),可以通过社区许可计划免费获得整套控件。注意:我为Syncfusion工作。

#15


17  

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.

我自己还没有必要使用它,但确实看起来很有趣。

#16


14  

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,这在您的情况下是理想的。

#17


13  

I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel

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

#18


13  

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)

(免责声明:我为SoftArtisans工作,这是一家制作OfficeWriter的公司)

#19


13  

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. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages.

OpenXML也是一个很好的选择,有助于避免在服务器上安装MS Excel。Microsoft提供的Open XML SDK 2.0简化了操作Open XML包和包中的底层Open XML架构元素的任务。 Open XML应用程序编程接口(API)封装了开发人员在Open XML包上执行的许多常见任务。

Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server

检查一下OpenXML:替代方法有助于避免在服务器上安装MS Excel

#20


13  

The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. 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.

各种Office 2003 XML库可以很好地用于较小的excel文件。但是,我发现以XML格式保存的大型工作簿的大小是一个问题。例如,我使用的工作簿在新的(并且承认更紧凑的)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). but both work independant of Excel itself.

两者都不便宜(我认为分别为500美元和800美元)。但两者都独立于Excel本身。

What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.

我很好奇的是OpenOffice.org之类的Excel输出模块。我想知道它们是否可以从Java移植到.Net。

#21


11  

IKVM + POI

IKVM + POI

Or, you could use the Interop ...

或者,您可以使用Interop ...

#22


11  

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 Literals,并在C#中做其他事情。)

#23


11  

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)提供了非常好的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 (e.g. ExcelLibrary).

如果您的导出旨在执行服务器端,并强调要导出的数据并且没有指向UI的链接,那么我会选择其中一个免费的开源选项(例如ExcelLibrary)。

I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.

我以前参与过试图在Microsoft Office套件上使用服务器端自动化的项目。根据这一经验,我强烈建议不要采用这种方法。

#24


11  

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文件,它可能会帮助您

#25


11  

You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation
See below sample:

您可以使用此库创建格式良好的Excel文件:http://officehelper.codeplex.com/documentation请参阅以下示例:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

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

#26


11  

I've just recently used FlexCel.NET and found it to be an excellent library! 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.

我刚刚使用FlexCel.NET,发现它是一个很棒的库!我不是说太多的软件产品。没有必要在这里给出整个销售宣传,你可以阅读他们网站上的所有功能。

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 Automation只是一个痛苦的整个世界。

#27


9  

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

bolton.

#28


9  

The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool. The Open XML Productivity Tool comes with the Open XML SDK installation. The tool reverse engineers any Excel file into C# code. The C# code can then be used to re-generate that file.

从C#创建Excel文件的最简单,最快捷的方法是使用Open XML Productivity Tool。 Open XML Productivity Tool附带Open XML SDK安装。该工具将任何Excel文件反向工程为C#代码。然后可以使用C#代码重新生成该文件。

An overview of the process involved is:

所涉及的过程概述如下:

  1. Install the Open XML SDK with the tool.
  2. 使用该工具安装Open XML SDK。

  3. Create an Excel file using the latest Excel client with desired look. Name it DesiredLook.xlsx.
  4. 使用具有所需外观的最新Excel客户端创建Excel文件。将其命名为DesiredLook.xlsx。

  5. With the tool open DesiredLook.xlsx and click the Reflect Code button near the top. 如何在不安装Ms Office的情况下在C#中创建Excel(.XLS和.XLSX)文件?
  6. 使用该工具打开DesiredLook.xlsx并单击顶部附近的Reflect Code按钮。

  7. The C# code for your file will be generated in the right pane of the tool. Add this to your C# solution and generate files with that desired look.
  8. 您的文件的C#代码将在该工具的右侧窗格中生成。将其添加到您的C#解决方案并生成具有所需外观的文件。

As a bonus, this method works for any Word and PowerPoint files. As the C# developer, you will then make changes to the code to fit your needs.

作为奖励,此方法适用于任何Word和PowerPoint文件。作为C#开发人员,您将对代码进行更改以满足您的需求。

I have developed a simple WPF app on github which will run on Windows for this purpose. There is a placeholder class called GeneratedClass where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this:

我在github上开发了一个简单的WPF应用程序,它将在Windows上运行以实现此目的。有一个名为GeneratedClass的占位符类,您可以在其中粘贴生成的代码。如果您返回该文件的一个版本,它将生成如下的excel文件:

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

#29


8  

Look at samples how to create Excel files.

查看示例如何创建Excel文件。

There are examples in C# and VB.NET

C#和VB.NET中有一些例子

It manages XSL XSLX and CSV Excel files.

它管理XSL XSLX和CSV Excel文件。

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

#30


7  

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作为sylk生成excelsheets,现在我们也在寻找excelgenerater。

The advantages for sylk are, you can format the cells.

sylk的优点是,您可以格式化单元格。

#1


910  

You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:

您可以使用名为ExcelLibrary的库。这是一个免费的开源库,发布在Google Code上:

ExcelLibrary

This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.

这看起来是您上面提到的PHP ExcelWriter的一个端口。它还不会写入新的.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,可让您使用DataSet和DataTable轻松处理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 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. It seems to be more actively updated and documented as well.

如评论中所述,每个库都有一些已知的错误。总之,随着时间的推移,EPPlus似乎是最好的选择。它似乎也更积极地更新和记录。

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
EPPlus - GNU Lesser General Public License (LGPL)

这里有几个链接供快速参考:ExcelLibrary - GNU较小GPL EPPlus - GNU较宽松通用公共许可证(LGPL)

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. You can also manually create Excel files, but the above functionality is what really impressed me.

创建Excel文件就像这样简单。您也可以手动创建Excel文件,但上述功能给我留下了深刻的印象。

#2


512  

If you are happy with the xlsx format, try my codeplex GitHub project. EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff.

如果您对xlsx格式感到满意,请尝试我的codeplex GitHub项目。 EPPlus。从ExcelPackage的源代码开始,但今天它完全重写。支持范围,单元格样式,图表,形状,图片,名称范围,自动过滤器和许多其他东西。

#3


154  

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). NPOI 2.0 (Alpha) also supports XLSX.

    NPOI for .XLS格式(Office 2003)。 NPOI 2.0(Alpha)也支持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

NPOI与Excel表和动态图表

#4


148  

And what about using Open XML SDK 2.0 for Microsoft Office?

那么使用Open XML SDK 2.0 for Microsoft Office呢?

A few benefits:

一些好处:

  • Doesn't require Office installed
  • 不需要安装Office

  • Made by Microsoft = decent MSDN documentation
  • 由Microsoft制作=体面的MSDN文档

  • Just one .Net dll to use in project
  • 只需一个.Net dll即可在项目中使用

  • SDK comes with many tools like diff, validator, etc
  • SDK附带了许多工具,如diff,validator等

Links:

#5


98  

You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB.

您可以使用OLEDB来创建和操作Excel文件。检查:使用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:

编辑 - 更多链接:

#6


75  

The commercial solution, SpreadsheetGear for .NET will do it.

商业解决方案,SpreadsheetGear for .NET将会这样做。

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

#7


59  

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. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites.

如果XLSX是必须的:ExcelPackage是一个良好的开端,但在开发人员退出工作时就已经死了。 ExML从那里获得并添加了一些功能。 ExML不是一个糟糕的选择,我仍然在几个生产网站中使用它。

For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX.

但是,对于我的所有新项目,我使用的是NPOI,Apache POI的.NET端口。 NPOI 2.0(Alpha)也支持XLSX。

#8


57  

An extremely lightweight option may be to use HTML tables. Just create head, body, and table tags in a file, and save it as a file with an .xls extension. There are Microsoft specific attributes that you can use to style the output, including formulas.

一个非常轻量级的选项可能是使用HTML表。只需在文件中创建head,body和table标签,并将其另存为扩展名为.xls的文件。您可以使用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. This technique could be used if you were coding a console app, desktop app, or service.

我意识到您可能没有在Web应用程序中对此进行编码,但这里是通过HTML表格组成Excel文件的示例。如果您正在编写控制台应用程序,桌面应用程序或服务,则可以使用此技术。

#9


44  

You can use ExcelXmlWriter.

您可以使用ExcelXmlWriter。

It works fine.

它工作正常。

#10


42  

You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use.

您实际上可能想要查看互操作类。你说没有OLE(这不是),但互操作类很容易使用。

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在此环境中运行时出现死锁或死锁。

#11


41  

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. It can be used by any .NET language like C# and Visual Basic (VB).

它提供了一种面向对象的方式来操作文件(类似于VBA),而无需处理XML文档的麻烦。它可以被任何.NET语言使用,如C#和Visual Basic(VB)。

ClosedXML allows you to create Excel 2007/2010 files without the Excel application. The typical example is creating Excel reports on a web server:

ClosedXML允许您在不使用Excel应用程序的情况下创建Excel 2007/2010文件。典型示例是在Web服务器上创建Excel报告:

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

#12


30  

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库从DataSet,DataTable或List <>导出到真正的Excel 2007 .xlsx文件中:

http://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:

将此类添加到应用程序后,只需一行代码就可以将DataSet导出到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出现在您的服务器上。

#13


23  

You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema.

您可以考虑使用XML Spreadsheet 2003格式创建文件。这是一种使用记录良好的架构的简单XML格式。

#14


19  

Syncfusion Essential XlsIO can do this. It has no dependency on Microsoft office and also has specific support for different platforms.

Syncfusion Essential XlsIO可以做到这一点。它不依赖于Microsoft办公室,并且对不同平台也有特定支持。

  • ASP.NET
  • ASP.NET MVC
  • UWP
  • Xamarin
  • WPF and Windows Forms
  • WPF和Windows窗体

  • Windows Service and batch based operations
  • Windows服务和基于批处理的操作

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). Note: I work for Syncfusion.

如果您符合资格(收入不到100万美元),可以通过社区许可计划免费获得整套控件。注意:我为Syncfusion工作。

#15


17  

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.

我自己还没有必要使用它,但确实看起来很有趣。

#16


14  

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,这在您的情况下是理想的。

#17


13  

I agree about generating XML Spreadsheets, here's an example on how to do it for C# 3 (everyone just blogs about it in VB 9 :P) http://www.aaron-powell.com/linq-to-xml-to-excel

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

#18


13  

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)

(免责声明:我为SoftArtisans工作,这是一家制作OfficeWriter的公司)

#19


13  

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. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages.

OpenXML也是一个很好的选择,有助于避免在服务器上安装MS Excel。Microsoft提供的Open XML SDK 2.0简化了操作Open XML包和包中的底层Open XML架构元素的任务。 Open XML应用程序编程接口(API)封装了开发人员在Open XML包上执行的许多常见任务。

Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server

检查一下OpenXML:替代方法有助于避免在服务器上安装MS Excel

#20


13  

The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. 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.

各种Office 2003 XML库可以很好地用于较小的excel文件。但是,我发现以XML格式保存的大型工作簿的大小是一个问题。例如,我使用的工作簿在新的(并且承认更紧凑的)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). but both work independant of Excel itself.

两者都不便宜(我认为分别为500美元和800美元)。但两者都独立于Excel本身。

What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.

我很好奇的是OpenOffice.org之类的Excel输出模块。我想知道它们是否可以从Java移植到.Net。

#21


11  

IKVM + POI

IKVM + POI

Or, you could use the Interop ...

或者,您可以使用Interop ...

#22


11  

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 Literals,并在C#中做其他事情。)

#23


11  

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)提供了非常好的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 (e.g. ExcelLibrary).

如果您的导出旨在执行服务器端,并强调要导出的数据并且没有指向UI的链接,那么我会选择其中一个免费的开源选项(例如ExcelLibrary)。

I have previously been involved with projects that attempted to use server side automation on the Microsoft Office suite. Based on this experience I would strongly recommend against that approach.

我以前参与过试图在Microsoft Office套件上使用服务器端自动化的项目。根据这一经验,我强烈建议不要采用这种方法。

#24


11  

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文件,它可能会帮助您

#25


11  

You can create nicely formatted Excel files using this library: http://officehelper.codeplex.com/documentation
See below sample:

您可以使用此库创建格式良好的Excel文件:http://officehelper.codeplex.com/documentation请参阅以下示例:

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

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

#26


11  

I've just recently used FlexCel.NET and found it to be an excellent library! 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.

我刚刚使用FlexCel.NET,发现它是一个很棒的库!我不是说太多的软件产品。没有必要在这里给出整个销售宣传,你可以阅读他们网站上的所有功能。

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 Automation只是一个痛苦的整个世界。

#27


9  

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

bolton.

#28


9  

The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool. The Open XML Productivity Tool comes with the Open XML SDK installation. The tool reverse engineers any Excel file into C# code. The C# code can then be used to re-generate that file.

从C#创建Excel文件的最简单,最快捷的方法是使用Open XML Productivity Tool。 Open XML Productivity Tool附带Open XML SDK安装。该工具将任何Excel文件反向工程为C#代码。然后可以使用C#代码重新生成该文件。

An overview of the process involved is:

所涉及的过程概述如下:

  1. Install the Open XML SDK with the tool.
  2. 使用该工具安装Open XML SDK。

  3. Create an Excel file using the latest Excel client with desired look. Name it DesiredLook.xlsx.
  4. 使用具有所需外观的最新Excel客户端创建Excel文件。将其命名为DesiredLook.xlsx。

  5. With the tool open DesiredLook.xlsx and click the Reflect Code button near the top. 如何在不安装Ms Office的情况下在C#中创建Excel(.XLS和.XLSX)文件?
  6. 使用该工具打开DesiredLook.xlsx并单击顶部附近的Reflect Code按钮。

  7. The C# code for your file will be generated in the right pane of the tool. Add this to your C# solution and generate files with that desired look.
  8. 您的文件的C#代码将在该工具的右侧窗格中生成。将其添加到您的C#解决方案并生成具有所需外观的文件。

As a bonus, this method works for any Word and PowerPoint files. As the C# developer, you will then make changes to the code to fit your needs.

作为奖励,此方法适用于任何Word和PowerPoint文件。作为C#开发人员,您将对代码进行更改以满足您的需求。

I have developed a simple WPF app on github which will run on Windows for this purpose. There is a placeholder class called GeneratedClass where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this:

我在github上开发了一个简单的WPF应用程序,它将在Windows上运行以实现此目的。有一个名为GeneratedClass的占位符类,您可以在其中粘贴生成的代码。如果您返回该文件的一个版本,它将生成如下的excel文件:

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

#29


8  

Look at samples how to create Excel files.

查看示例如何创建Excel文件。

There are examples in C# and VB.NET

C#和VB.NET中有一些例子

It manages XSL XSLX and CSV Excel files.

它管理XSL XSLX和CSV Excel文件。

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

#30


7  

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作为sylk生成excelsheets,现在我们也在寻找excelgenerater。

The advantages for sylk are, you can format the cells.

sylk的优点是,您可以格式化单元格。