如何使用Linq写入Excel电子表格?

我正在写一个应用程序,我需要从数据库中检索一些行并将其转储到Excel电子表格中。 我正在使用Linq来检索这些行。

是否有可能将这些行直接转储到Excel工作表中的对应部分(Excel中的一个单元格对应于数据库中的一个单元格)?

没有直接的方法来连接这两个。 这听起来像是你希望LINQ to SQL来处理查询生成,而不是O / R映射(因为Excel不知道如何处理来自LINQ的对象 – 它们看起来不再像数据行一样)。 您可以通过调用(datacontext).GetCommand(yourLinqQueryHere)来完成第一部分,然后将其作为SqlCommand中的CommandText运行。 调用ExecuteReader(),然后GetSchemaTable()来找出列的顺序。 然后(假设你自动化Excel)将(DbDataReader).GetValues()的结果传递给Excel的(工作表).Row [x] .Values,并将结果input。您可能需要重新sorting。 如果您没有自动化Excel,则需要使用OleDbConnection的Excel OLEDB提供程序转储值,或使用第三方组件生成电子表格。

我个人不喜欢使用图书馆这样的事情,因为我总是发现它在稍后的某个时间限制…

我使用reflection来生成列标题并获取每行的单元格值。 如果您使用.NET Framework 3.5,则可以利用扩展方法,以便将任何IEnumerable<object>导出到Excel XDocument文件中。

我是这样做的:

 using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace YourNameSpace { public static class ExcelExportExtensions { public static XDocument ToExcelXml(this IEnumerable<object> rows) { return rows.ToExcelXml("Sheet1"); } public static XDocument ToExcelXml(this IEnumerable<object> rows, string sheetName) { sheetName = sheetName.Replace("/", "-"); sheetName = sheetName.Replace("\\", "-"); XNamespace mainNamespace = "urn:schemas-microsoft-com:office:spreadsheet"; XNamespace o = "urn:schemas-microsoft-com:office:office"; XNamespace x = "urn:schemas-microsoft-com:office:excel"; XNamespace ss = "urn:schemas-microsoft-com:office:spreadsheet"; XNamespace html = "http://www.w3.org/TR/REC-html40"; XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); var headerRow = from p in rows.First().GetType().GetProperties() select new XElement(mainNamespace + "Cell", new XElement(mainNamespace + "Data", new XAttribute(ss + "Type", "String"), p.Name)); //Generate header using reflection XElement workbook = new XElement(mainNamespace + "Workbook", new XAttribute(XNamespace.Xmlns + "html", html), new XAttribute(XName.Get("ss", "http://www.w3.org/2000/xmlns/"), ss), new XAttribute(XName.Get("o", "http://www.w3.org/2000/xmlns/"), o), new XAttribute(XName.Get("x", "http://www.w3.org/2000/xmlns/"), x), new XAttribute(XName.Get("xmlns", ""), mainNamespace), new XElement(o + "DocumentProperties", new XAttribute(XName.Get("xmlns", ""), o), new XElement(o + "Author", "Smartdesk Systems Ltd"), new XElement(o + "LastAuthor", "Smartdesk Systems Ltd"), new XElement(o + "Created", DateTime.Now.ToString()) ), //end document properties new XElement(x + "ExcelWorkbook", new XAttribute(XName.Get("xmlns", ""), x), new XElement(x + "WindowHeight", 12750), new XElement(x + "WindowWidth", 24855), new XElement(x + "WindowTopX", 240), new XElement(x + "WindowTopY", 75), new XElement(x + "ProtectStructure", "False"), new XElement(x + "ProtectWindows", "False") ), //end ExcelWorkbook new XElement(mainNamespace + "Styles", new XElement(mainNamespace + "Style", new XAttribute(ss + "ID", "Default"), new XAttribute(ss + "Name", "Normal"), new XElement(mainNamespace + "Alignment", new XAttribute(ss + "Vertical", "Bottom") ), new XElement(mainNamespace + "Borders"), new XElement(mainNamespace + "Font", new XAttribute(ss + "FontName", "Calibri"), new XAttribute(x + "Family", "Swiss"), new XAttribute(ss + "Size", "11"), new XAttribute(ss + "Color", "#000000") ), new XElement(mainNamespace + "Interior"), new XElement(mainNamespace + "NumberFormat"), new XElement(mainNamespace + "Protection") ), new XElement(mainNamespace + "Style", new XAttribute(ss + "ID", "Header"), new XElement(mainNamespace + "Font", new XAttribute(ss + "FontName", "Calibri"), new XAttribute(x + "Family", "Swiss"), new XAttribute(ss + "Size", "11"), new XAttribute(ss + "Color", "#000000"), new XAttribute(ss + "Bold", "1") ) ) ), // close styles new XElement(mainNamespace + "Worksheet", new XAttribute(ss + "Name", sheetName /* Sheet name */), new XElement(mainNamespace + "Table", new XAttribute(ss + "ExpandedColumnCount", headerRow.Count()), new XAttribute(ss + "ExpandedRowCount", rows.Count() + 1), new XAttribute(x + "FullColumns", 1), new XAttribute(x + "FullRows", 1), new XAttribute(ss + "DefaultRowHeight", 15), new XElement(mainNamespace + "Column", new XAttribute(ss + "Width", 81) ), new XElement(mainNamespace + "Row", new XAttribute(ss + "StyleID", "Header"), headerRow), from contentRow in rows select new XElement(mainNamespace + "Row", new XAttribute(ss + "StyleID", "Default"), from p in contentRow.GetType().GetProperties() select new XElement(mainNamespace + "Cell", new XElement(mainNamespace + "Data", new XAttribute(ss + "Type", "String"), p.GetValue(contentRow, null))) /* Build cells using reflection */ ) ), //close table new XElement(x + "WorksheetOptions", new XAttribute(XName.Get("xmlns", ""), x), new XElement(x + "PageSetup", new XElement(x + "Header", new XAttribute(x + "Margin", "0.3") ), new XElement(x + "Footer", new XAttribute(x + "Margin", "0.3") ), new XElement(x + "PageMargins", new XAttribute(x + "Bottom", "0.75"), new XAttribute(x + "Left", "0.7"), new XAttribute(x + "Right", "0.7"), new XAttribute(x + "Top", "0.75") ) ), new XElement(x + "Print", new XElement(x + "ValidPrinterInfo"), new XElement(x + "HorizontalResolution", 600), new XElement(x + "VerticalResolution", 600) ), new XElement(x + "Selected"), new XElement(x + "Panes", new XElement(x + "Pane", new XElement(x + "Number", 3), new XElement(x + "ActiveRow", 1), new XElement(x + "ActiveCol", 0) ) ), new XElement(x + "ProtectObjects", "False"), new XElement(x + "ProtectScenarios", "False") ) // close worksheet options ) // close Worksheet ); xdoc.Add(workbook); return xdoc; } } } 

我还创build了另一个扩展方法来缓解在Webscheme中返回XDocument:

 public static DownloadableFile ToDownloadableXmlFileForExcel2003(this System.Xml.Linq.XDocument file, string fileName) { MemoryStream ms = new MemoryStream(); XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() { Encoding = Encoding.UTF8 }; XmlWriter xmlWriter = XmlWriter.Create(ms, xmlWriterSettings); file.Save(xmlWriter); //.Save() adds the <xml /> header tag! xmlWriter.Close(); //Must close the writer to dump it's content its output (the memory stream) DownloadableFile dbf = new DownloadableFile { FileName = String.Format("{0}.xls", fileName.Replace(" ", "")), Content = ms.ToArray(), MimeType = "application/vnd.ms-excel" }; ms.Close(); ms.Dispose(); return dbf; } 

希望这可以帮助!

您可以:

看看这个Excel数据对象提供程序 。 我还没有亲自使用它的写作function,我适应了阅读支持,以允许序号(以及命名)列标识符,但它可能是在正确的方向迈出的一步。 请记住,除非在目标计算机上安装了Excel 2003+,否则不能写入或读取XLSX文件; 标准的XLS文件将在任何Windows盒子上工作。

我可以在这里find具有序列的改编版本。 如果您决定使用代码,您可能会发现在当前版本(在上面的链接)中实现它是必要/有用的。 我的版本是从版本2.0和2.5的function混合 – 它具有所有的阅读function(大约2.5升级),但没有写作。 哦,和版本2.0或2.5不同,我的版本并不要求Excel文档中的第一张被命名为“Sheet1”。

希望有所帮助!

用LINQ to XML写入Excel XML

非常简单,不需要外部库,并使用reflection将任何IEnumerable转换为工作表!

http://scottstjohn.wordpress.com/2011/04/02/write-to-excel-xml-with-linq-to-xml/

正如作者所描述的,斯科特·圣约翰(Scott St. John)(我从他的url猜测这个 – 他的网站上没有任何生物信息):

我发现了一个非常好的扩展类来将任何IEnumerable写入Excel XML电子表格。 请参阅C#使用Linq by bounav写入Excel。 我做了几个修改,因为希望能够添加新的IEnumerables作为工作表。 看到一个例子和下面的源代码

我几乎将他的代码复制/粘贴到LINQPad中的MyExtensions中,并立即使用它。

最快的解决scheme是创build一个csv文件:

 col1, colb, colc col1, colb, colc 

Excel对csv文件效果很好。

你用LINQ检索你的数据的事实是不相干的。 你真正想要写的是一个好的库。 一旦你得到了,你可以简单地遍历你的结果,在Excel工作表中创build行。

就图书馆而言,我曾经使用NPOI ,这很好。