我有一个包含50多列和100000多行的DataTable。我需要将整个DataTable值转储到Excel文件中。任何人都可以帮助ASP.net中的C#代码。我需要每个列值都在一个单元格。确切地说,我需要Excel文件中的DataTable的精确副本。请帮助。
谢谢, 基兰
答案 0 :(得分:1)
查看此示例的ExporttoExcel
函数。它会对你有帮助。
答案 1 :(得分:0)
你可以调用这个方法,只需传入你的DataTable:
public static void DumpExcel(DataTable dataTable)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("DataTable");
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
for (int i = 1; i <= dataTable.Columns.Count; i++)
{
worksheet.Column(i).AutoFit();
if (dataTable.Columns[i - 1].DataType == System.Type.GetType("System.DateTime"))
{
worksheet.Column(i).Style.Numberformat.Format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
}
}
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=table.xlsx");
HttpContext.Current.Response.BinaryWrite(package.GetAsByteArray());
HttpContext.Current.Response.End();
}
}
答案 2 :(得分:0)
public void ExportToExcel(string strFileName, DataTable dt)
{
try
{
if (dt != null && dt.Rows.Count > 0)
{
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
ExportToExcel(strFileName, gv);
}
else
{
BindScript(this.Page, "excelError", "alert('No Data to Generate Excel !')");
}
}
catch (Exception ex)
{
BindScript(this.Page, "excelError", "alert('Some error occured " + ex.Message + "')");
}
}
private void ExportToExcel(string strFileName, GridView gv)
{
try
{
if (gv.Rows.Count > 0)
{
//Page page = new Page();
//HtmlForm form = new HtmlForm();
//Response.ClearContent();
//Response.Buffer = true;
//Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
//Response.ContentType = "application/excel";
////System.Text.StringBuilder sb = new System.Text.StringBuilder();
//StringWriter sw = new StringWriter();
//HtmlTextWriter htw = new HtmlTextWriter(sw);
//form.Controls.Add(gv);
//page.Controls.Add(form);
////form.RenderControl(htw);
//HttpContext.Current.Server.Execute(page, sw, true);
//Response.Write(sw.ToString());
//Response.Flush();
//Response.End();
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
//Get the HTML for the control.
gv.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName);
EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
else
{
BindScript(this.Page, "excelError", "alert('No Data to Generate Excel !')");
}
}
catch (Exception ex)
{
BindScript(this.Page, "excelError", "alert('Some error occured " + ex.Message + "')");
}
}