简体   繁体   English

使用C#将数据导出到Excel(包括格式)

[英]Export data to Excel (including formatting) using C#

I have a DataTable in my program which I have previously exported to excel using a CSV file. 我的程序中有一个DataTable,之前我已使用CSV文件将其导出到excel。 However, I want to conditionally format the backgroun colour of cells - which obviously needs a new approach. 但是,我想有条件地格式化单元格的背景颜色-显然需要一种新方法。

The issue is this - the computer where the software will run does not have Excel. 问题是这样的-将运行该软件的计算机没有Excel。 So I cannot go down the route of calling the Excel api. 因此,我无法沿途调用Excel api。

Is there an easy way of doing this that I have missed? 有没有一种我错过的简便方法? If not, is the format of Excel files published or how can I achieve this goal? 如果不是,是否发布了Excel文件的格式,或者如何实现此目标?

Thanks. 谢谢。


EDIT: 编辑:

For anyone else that is interested, I eventually found this post which provides the simplest method I have found. 对于其他感兴趣的人,我最终找到了这篇文章该文章提供了我找到的最简单的方法。 Works with Excel 2003. 适用于Excel 2003。

Which version of excel? 哪个版本的excel? If you need excel 2003, then take a look at : http://www.carlosag.net/Tools/ExcelXmlWriter/ 如果您需要excel 2003,请查看: http : //www.carlosag.net/Tools/ExcelXmlWriter/

If you're ok with excel 2007, then there's: http://excelpackage.codeplex.com/ (open source) or http://msdn.microsoft.com/en-us/library/bb448854.aspx (official MS product) 如果您对excel 2007没问题,那么可以使用: http : //excelpackage.codeplex.com/ (开放源代码)或http://msdn.microsoft.com/zh-cn/library/bb448854.aspx (官方MS产品)

Check out NPOI , which is a .NET port of POI, a free MS office interop library. NPOI ,它是POI的.NET端口,POI是免费的MS Office互操作库。 It's powerful and fairly straightforward to learn (though the documentation is iffy). 它的功能强大且相当简单易学(虽然文档玄乎)。 I would read through some of the past posts here on NPOI (there aren't all that many) to become familiar with a few frustrating gotchas that are not so much problems as things that are counterintuitive and not always obvious from the documentation. 我会仔细阅读NPOI上的一些过去的帖子(并没有那么多),以熟悉一些令人沮丧的陷阱,这些问题不是很直觉,而是从文档中直觉得出的。

But once you get past the lack of a good primer it's an awesome library. 但是一旦您克服了缺少好的入门书的知识,那就是一个了不起的库。

I assume you're talking about xls format. 我假设您是在谈论xls格式。 If you can use the newer XML based xlsx format, it's a totally different problem. 如果您可以使用更新的基于XML的xlsx格式,那将是完全不同的问题。 You just need to write XML, the format is available on Microsoft's web site. 您只需要编写XML,该格式就可以在Microsoft的网站上找到。 There may be are (see other answer) tools that can help with this, though personally, I always just use NPOI and write XLS files to be sure anyone can open them. 可能是 (看其他的答案)工具,可以帮助这一点,虽然就个人而言,我始终只使用NPOI和写入的XLS文件,以确保任何人都可以打开它们。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM