【发布时间】:2015-04-15 10:31:43
【问题描述】:
我在 Excel 中遇到与我尝试从列表视图(ASP 和 C#)导出的数据相关的错误。
为了澄清,我将 ListView 转换为 DataTable,因为我事先遇到了错误。
所有这些都是通过单击按钮来处理的,创建了 excel 文档,但是打开它时出现错误,并且只显示标题。
知道我做错了什么吗?我的怀疑是在LoadFromDataTable 中添加dt 会导致这种情况,但在调试中没有任何错误出现 - 任何指针都将不胜感激。
Excel 错误: We found a problem with some content in 'Test_List.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
背后的 C# 代码
protected void csv_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Ref", typeof(string)));
dt.Columns.Add(new DataColumn("Company", typeof(string)));
dt.Columns.Add(new DataColumn("Email", typeof(string)));
dt.Columns.Add(new DataColumn("Telephone", typeof(string)));
foreach(ListViewDataItem li in ListView1.Items)
{
if (li.ItemType == ListViewItemType.DataItem)
{
DataRow dr = dt.NewRow();
dr["Ref"] = ((Label)li.FindControl("lblRef")).Text;
dr["Company"] = ((Label)li.FindControl("lblCmp")).Text;
dr["Email"] = ((Label)li.FindControl("lblEmail")).Text;
dr["Telephone"] = ((Label)li.FindControl("lblTele")).Text;
dt.Rows.Add(dr);
}
}
using (ExcelPackage pck = new ExcelPackage())
{
// creating worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Test_List");
// load database to sheet, start from A1, print column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
//loop through rows in datatable to rows in excel
Response.ContentType = "application/vnd.openxmlformats-officedocument,spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Test_List.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
【问题讨论】:
标签: c# excel listview datatable