将数据从DataTable导出到Excel文件

问题描述:

我有DataTable对象。我如何将它导出到XLS文件中? 我试图通过数据网格将数据从DataTable导出到Excel文件

DataGrid dgGrid = new DataGrid(); 
dgGrid.DataSource = dt; 
dgGrid.DataBind(); 
dgGrid.RenderControl(hw); 

渲染,但该文件是非常大和OutOfMemoryException出现。可以使用http://epplus.codeplex.com/。 我需要C#功能。

好了,在这里找到一个解决方案:http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C

只需下载epplus库和调用方法:

private void GenerateExcel(DataTable dataToExcel, string excelSheetName) 
     { 
      string fileName = "ByteOfCode"; 
      string currentDirectorypath = Environment.CurrentDirectory; 
      string finalFileNameWithPath = string.Empty; 

      fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy")); 
      finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName); 

      //Delete existing file with same file name. 
      if (File.Exists(finalFileNameWithPath)) 
       File.Delete(finalFileNameWithPath); 

      var newFile = new FileInfo(finalFileNameWithPath); 

      //Step 1 : Create object of ExcelPackage class and pass file path to constructor. 
      using (var package = new ExcelPackage(newFile)) 
      { 
       //Step 2 : Add a new worksheet to ExcelPackage object and give a suitable name 
       ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName); 

       //Step 3 : Start loading datatable form A1 cell of worksheet. 
       worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.None); 

       //Step 4 : (Optional) Set the file properties like title, author and subject 
       package.Workbook.Properties.Title = @"This code is part of tutorials available at http://bytesofcode.hubpages.com"; 
       package.Workbook.Properties.Author = "Bytes Of Code"; 
       package.Workbook.Properties.Subject = @"Register here for more http://hubpages.com/_bytes/user/new/"; 

       //Step 5 : Save all changes to ExcelPackage object which will create Excel 2007 file. 
       package.Save(); 

       MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName) 
        , "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information); 
      } 
     } 

首先,Google是你最好的朋友。你也可以在这个网站上搜索。

一些解决方案:

  • 你可以写与SQL的Excel文件。
  • 您可以使用对Microsoft Office库的引用来创建Excel文件
  • 您可以编写一个XML文件。
+2

我知道谷歌是我最好的朋友,但我没有找到解决方案是如何做到这一点正好,所以我在这里发帖的问题 – ihorko 2012-08-03 14:19:40

有很多选项,其中之一是Access OLE DB Provider,其中也运行DataTables。

如果您希望对文档提供更精细的支持,我建议您使用Open XML SDK 2.0,只有.xmlx。

对于原始数据,我认为访问OLE DB(也被认为是ACE提供者)是最好的选择,因为它可以实现类似数据库的体验。 Open XML假设了XML的相当好的知识并且愿意尝试更多。另一方面,您可以应用格式,添加公式和其他高级功能。

+0

谢谢,但你的评论它不能解决我的问题 – ihorko 2012-08-03 14:19:16

+0

也许尝试使你的问题更具体,它不清楚你在找什么。比我们将能够更有效地帮助你。 – 2012-08-03 14:22:09