【问题标题】:ListView not exporting data correctly to ExcelListView 未将数据正确导出到 Excel
【发布时间】: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


    【解决方案1】:

    我在您的示例中遇到的问题是列表视图未正确转换为数据表,这可能是也可能不是您的电子表格抛出该无用错误的原因。

    如果您在dr["ref"] 上调试并深入挖掘,我认为该字符串不包含标签文本。

    将listview剪成datatable位,从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();
                            }
                        }
                    }
                }
            }
    

    【讨论】:

    • 好的,谢谢你的建议,有工作总比没有好!
    猜你喜欢
    • 2012-05-16
    • 2012-05-20
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多