从数据表到Excel文件导出数据 [英] Export data from DataTable to Excel file
本文介绍了从数据表到Excel文件导出数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有DataTable对象。我怎样才能将其导出到XLS文件?
我试图通过DataGrid中以使其
I have DataTable object. How can I export it into an XLS file? I tried to render it via DataGrid
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
但文件非常大,并出现 OutOfMemoryException异常
。
我可以使用 HTTP://epplus.$c$cplex.com/ 。
我需要C#的功能。
I can use http://epplus.codeplex.com/. I need C# function.
推荐答案
好吧,在这里找到一个解决方案:的http://bytesof$c$c.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C
Ok, find a solution here: http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C
只要下载epplus库和呼叫方式:
Just download epplus library and call method:
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);
}
}
这篇关于从数据表到Excel文件导出数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文