将数据从DataTable导出到Excel文件

我有DataTable对象。 我如何将它导出到XLS文件? 我试图通过DataGrid呈现它

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

但文件非常大,出现OutOfMemoryException

我可以使用http://epplus.codeplex.com/ 。 我需要C#function。

有许多选项,其中之一就是访问OLE DB提供程序 ,该提供程序也按照DataTables进行操作。

如果你想对文档提供更好的支持,我推荐Open XML SDK 2.0 ,只有.xmlx。

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

好的,在这里find一个解决scheme: 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是你最好的朋友。 你也可以在这个网站上search。

一些解决scheme

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