Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用Linq写入Excel电子表格?_C#_Linq_Excel_Interop - Fatal编程技术网

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

C# 如何使用Linq写入Excel电子表格?,c#,linq,excel,interop,C#,Linq,Excel,Interop,我正在编写一个应用程序,需要从数据库中检索一些行,并将它们转储到Excel电子表格中。我正在使用Linq检索这些行 是否可以将这些行直接转储到Excel工作表中的对应行中(Excel中的一个单元格对应于数据库中的一个单元格)?最快的解决方案是创建一个csv文件: col1, colb, colc col1, colb, colc Excel可以很好地处理csv文件。您可以: 创建一个CSV文件,该文件在大多数系统上与Excel关联 创建Excel工作表对象并手动填充它 使用XLS/XLSX生

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


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

最快的解决方案是创建一个csv文件:

col1, colb, colc
col1, colb, colc
Excel可以很好地处理csv文件。

您可以:

  • 创建一个CSV文件,该文件在大多数系统上与Excel关联
  • 创建Excel工作表对象并手动填充它
  • 使用XLS/XLSX生成控件。我已经使用了Spire.XLS
    • 看看这个。我个人没有使用过它的书写功能,我修改了阅读支持以允许序号(以及命名)列标识符,但这可能是朝着正确方向迈出的一步。请记住,除非目标计算机上安装了Excel 2003+,否则无法写入或读取XLSX文件;不过,标准XLS文件可以在任何Windows设备上使用

      可以找到我的带有序号列的改编版本。如果您决定使用该代码,您可能会发现在当前版本(在上面的链接)中实现该功能是必要的/有用的。我的版本是从和2.5的功能混合-它有所有的阅读功能(与一些2.5升级),但没有写作。哦-与2.0或2.5版不同,我的版本不要求Excel文档中的第一张工作表命名为“Sheet1”


      希望有帮助

      使用LINQ检索数据的事实有点无关紧要。你真正想要的是一个编写Excel的好库。一旦你得到了这些,你可以简单地迭代你的结果,在你的Excel工作表中创建行


      就我使用过的一个库而言,它非常棒。

      没有直接的方法来连接这两个库。听起来您希望LINQ到SQL来处理查询生成,但不希望处理O/R映射(因为Excel不知道如何处理从LINQ生成的对象—它们看起来不再像数据行)。您可以通过调用(datacontext).GetCommand(yourLinqQueryHere)来完成第一部分,然后将其作为SqlCommand中的CommandText运行。调用ExecuteReader(),然后调用GetSchemaTable()以确定列的顺序。然后(假设您正在自动化Excel),将(DbDataReader).GetValues()的结果传递给Excel的(工作表).Row[x].Values,它将显示结果。你可能需要重新订购东西。如果您不是在自动化Excel,您需要使用Jet OLEDB provider for Excel与OLEDB连接来转储值,或者使用第三方组件来生成电子表格。

      我个人不太喜欢使用库来处理这些事情,因为我发现它在以后的某个时候会受到限制

      我使用反射来生成列标题并获取每行的单元格值。如果您使用的是.NET framework 3.5,则可以利用扩展方法,以便将任何
      IEnumerable
      导出到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;
              }
          }
      }
      
      使用系统;
      使用System.Collections.Generic;
      使用System.Linq;
      使用System.Xml.Linq;
      名称空间YourNameSpace
      {
      公共静态类扩展
      {
      公共静态XDocument ToExcelXml(此IEnumerable行)
      {
      返回rows.ToExcelXml(“Sheet1”);
      }
      公共静态XDocument ToExcelXml(此IEnumerable行,字符串sheetName)
      {
      sheetName=sheetName。替换(“/”、“-”);
      sheetName=sheetName。替换(“\\”,“-”;
      XNamespace mainnespace=“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”;
      XHTML=”http://www.w3.org/TR/REC-html40";
      XDocument xdoc=新XDocument(新XDeclaration(“1.0”、“utf-8”、“是”);
      var headerRow=来自行中的p.First().GetType().GetProperties()
      选择新的XElement(mainNamespace+“单元格”,
      新XElement(mainNamespace+“数据”,
      新的XAttribute(ss+“Type”,“String”),p.Name));//使用反射生成标头
      XElement工作簿=新XElement(mainNamespace+“工作簿”,
      新的XAttribute(XNamespace.Xmlns+“html”,html),
      新的XAttribute(XName.Get(“ss”),”http://www.w3.org/2000/xmlns/",ss),,
      新的XAttribute(XName.Get(“o”)http://www.w3.org/2000/xmlns/(o),,
      新的XAttribute(XName.Get(“x”,”http://www.w3.org/2000/xmlns/",x),,
      新的XAttribute(XName.Get(“xmlns”),main名称空间,
      新XElement(o+“DocumentProperties”,
      新的XAttribute(XName.Get(“xmlns”),o,
      new XElement(o+“作者”、“智能桌面系统有限公司”),
      新XElement(o+“最新作者”、“智能桌面系统有限公司”),
      新的XElement(o+“已创建”,DateTime.Now.ToString())
      ),//结束文档属性
      新XElement(x+“Excel工作簿”,
      新的XAttribute(XName.Get(“xmlns”),x),
      新XElement(x+“窗高”,12750),
      新XElement(x+“窗宽”,24855),
      新XElement(x+“WindowTopX”,240),
      新XElement(x+“WindowTopY”,75),
      新的XElement(x+“ProtectStructure”、“False”),
      新的XElement(x+“保护窗口”、“假”)
      ),//结束工作簿
      新的XElement(mainNamespace+“样式”,
      新XElement(mainNamespace+“样式”,
      
      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;
      }