ListView 未将数据正确导出到 Excel
ListView not exporting data correctly to Excel
我在 excel 中收到与我尝试从列表视图(ASP 和 C#)导出的数据相关的错误。
澄清一下,我正在将 ListView 转换为 DataTable,因为我之前遇到了错误。
所有这些都是通过单击按钮处理的,创建了 excel 文档,但是打开它时出现错误,只显示 headers。
知道我做错了什么吗?我怀疑是在 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());
}
}
我在您的示例中遇到的问题是列表视图未正确转换为数据 table,这可能是也可能不是您的电子表格抛出无用错误的原因。
如果您在 dr["ref"]
上进行调试和深入研究,我认为该字符串不包含标签文本。
从列表视图到数据 table 位,从 SQL 数据库到 DataTable 再到 CSV。
就像这样,尽管您可以根据需要使用 xlsx:
protected void Csv_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString))
{
con.Open();
//stored procs are easier to modify than query strings
using (SqlCommand cmd = new SqlCommand("csvProc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
// build csv as comma sep string
string csv = string.Empty;
foreach(DataColumn col in dt.Columns)
{
// header row for csv
csv += col.ColumnName + ',';
}
// new line
csv += "\r\n";
foreach(DataRow row in dt.Rows)
{
foreach(DataColumn col in dt.Columns)
{
// add the data rows
csv += row[col.ColumnName].ToString().Replace(",", ";") + ',';
}
csv += "\r\n";
}
// download the csv file
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=TestList.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
}
}
}
我在 excel 中收到与我尝试从列表视图(ASP 和 C#)导出的数据相关的错误。
澄清一下,我正在将 ListView 转换为 DataTable,因为我之前遇到了错误。
所有这些都是通过单击按钮处理的,创建了 excel 文档,但是打开它时出现错误,只显示 headers。
知道我做错了什么吗?我怀疑是在 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());
}
}
我在您的示例中遇到的问题是列表视图未正确转换为数据 table,这可能是也可能不是您的电子表格抛出无用错误的原因。
如果您在 dr["ref"]
上进行调试和深入研究,我认为该字符串不包含标签文本。
从列表视图到数据 table 位,从 SQL 数据库到 DataTable 再到 CSV。
就像这样,尽管您可以根据需要使用 xlsx:
protected void Csv_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString))
{
con.Open();
//stored procs are easier to modify than query strings
using (SqlCommand cmd = new SqlCommand("csvProc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
// build csv as comma sep string
string csv = string.Empty;
foreach(DataColumn col in dt.Columns)
{
// header row for csv
csv += col.ColumnName + ',';
}
// new line
csv += "\r\n";
foreach(DataRow row in dt.Rows)
{
foreach(DataColumn col in dt.Columns)
{
// add the data rows
csv += row[col.ColumnName].ToString().Replace(",", ";") + ',';
}
csv += "\r\n";
}
// download the csv file
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=TestList.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
}
}
}