我在Excel文档中下载数据时收到错误Worksheet names cannot be empty
。以下是我的错误
protected void btnDownloadExcel_OnClick(object sender, EventArgs e)
{
try
{
DataTable dt = GetReportData();
if (dt.Rows.Count > 0)
{
string fileName = drpReports.SelectedItem.ToString();
using (XLWorkbook excel = new XLWorkbook())
{
//error from below line
excel.Worksheets.Add(dt);
excel.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
excel.Style.Font.Bold = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
using (var myMemoryStream = new MemoryStream())
{
excel.SaveAs(myMemoryStream);
myMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
HttpContext.Current.Response.End();
}
}
}
else
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "<script language='javascript'>alert('No records found. Please check the selection criteria.');</script>", false);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "<script language='javascript'>alert('Oops..!! some error occured. Please contact to administrator.');</script>", false);
log4net.ThreadContext.Properties["loginid"] = LoggedInUserDetails.LoginId.ToString();
Log.Error(ex.Message, ex);
}
}
我在将excel.Worksheets.Add(dt);
添加到Excel时,Datatable
收到错误消息。有人能告诉我我在哪里做错了。
答案 0 :(得分:2)
在尝试添加没有表名的DataTable时,我能够看到上述问题。当我尝试使用带有表名的DataTable时,它运行正常。在这种情况下,DataTable名称将保留为工作表的名称。
using ClosedXML.Excel;
using System;
using System.Data;
namespace ClosedXML_Test
{
class Program
{
/// <summary>
/// This example method generates a DataTable.
/// </summary>
static DataTable GetTable()
{
DataTable table = new DataTable("Test");//DataTable with name - works fine
//DataTable table = new DataTable("Test"); //DataTable without name - issue reproduced as you mentioned
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
static void Main(string[] args)
{
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add(GetTable());
workbook.SaveAs("Sample.xlsx");
workbook.Dispose();
System.Diagnostics.Process.Start("Sample.xlsx");
}
}
}
答案 1 :(得分:0)
protected void btnDownloadExcel_OnClick(object sender, EventArgs e)
{
try
{
DataTable dt = GetReportData();
if (dt.Rows.Count > 0)
{
string fileName = drpReports.SelectedItem.ToString();
string attachment = "attachment;filename=" + fileName + ' ' + DateTime.Now.ToShortDateString() + ".xlsx";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}
else
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "<script language='javascript'>alert('No records found. Please check the selection criteria.');</script>", false);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "<script language='javascript'>alert('Oops..!! some error occured. Please contact to administrator.');</script>", false);
log4net.ThreadContext.Properties["loginid"] = LoggedInUserDetails.LoginId.ToString();
Log.Error(ex.Message, ex);
}
}
答案 2 :(得分:0)
添加
YourDataTableName.TableName = "Enter_a_Name_same_as_Excelsheetname";
在宣布您的
之前XLWorkbook excel= new XLWorkbook()
或
var ws= excel.Worksheets.Add(table);
ws.Name="Enter_a_Name_same_as_Excelsheetname";