ListView无法正确导出数据到Excel

时间:2015-04-15 10:31:43

标签: c# excel listview datatable

我在excel中遇到与我尝试从listview(ASP& C#)导出的数据有关的错误。

为了澄清,我正在将ListView转换为DataTable,因为我手头有错误。

所有这些都是通过单击按钮处理的,excel文档已创建,但打开时会出现错误,只显示标题。

知道我做错了什么吗?我怀疑在dt中添加LoadFromDataTable会导致这种情况,但是调试中没有任何内容会出现错误 - 任何指针都会被感激地接收。

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());
        }
    }

1 个答案:

答案 0 :(得分:1)

我将在您的示例中使用的问题是listview没有正确转换为数据表,这可能是也可能不是您的spreadheeet抛出无用错误的原因。

如果您调试并深入挖掘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();
                        }
                    }
                }
            }
        }
相关问题