15

我在按钮单击事件的 aspx 页面上使用下面的代码来生成 csv 文件。当我不命名我的文件但尝试使用时,这有效: Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");

要将文件命名为 myfilename.csv,生成的 excel 表是网页的屏幕截图,而不是其中的文本。有人可以帮我解决这个问题。
谢谢!

DataGrid dg = new DataGrid();
dg.DataSource = GetData();
htmlTextWriter.WriteLine("<b>Details</b>");

//Get the html for the control
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;
dg.DataBind();
dg.RenderControl(htmlTextWriter);

//Write the HTML back to the browser.
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
//Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
this.EnableViewState = false;
Response.Write(textWriter.ToString());
Response.End();

private System.Data.DataTable GetData()
{
    System.Data.DataTable dt = new System.Data.DataTable("TestTable");
    dt.Columns.Add("SSN");
    dt.Columns.Add("Employee ID");
    dt.Columns.Add("Member Last Name");
    dt.Columns.Add("Member First Name");
    dt.Columns.Add("Patient Last Name");
    dt.Columns.Add("Patient First Name");
    dt.Columns.Add("Claim No.");
    dt.Columns.Add("Service Line No.");
    dt.Columns.Add("Error Code");
    dt.Columns.Add("Error Message");                
    dt.Rows.Add(123456789,4455,"asdf","asdf","sdfg","xzcv","dsfgdfg123",1234,135004,"some error");            
    dt.Rows.Add(123456788,3344,"rth","ojoij","poip","wer","aadf124",1233,135005,"Some Error");
    dt.Rows.Add(123456787,2233,"dfg","sdfg","vcxb","cxvb","UHCAL125",1223,135006,"another error");
    return dt;
}
4

4 回答 4

20

我不确定您在这里的目标是什么,因此我假设您希望在按钮单击事件中创建一个 CSV 文件并将其发送回用户。您当前所拥有的似乎是将控件的 HTML 写入 XLS 文件。

试试这个:

protected void Button1_Click(object sender, EventArgs e)
{
    var dataTable = GetData();
    StringBuilder builder = new StringBuilder();
    List<string> columnNames = new List<string>();
    List<string> rows = new List<string>();

    foreach (DataColumn column in dataTable.Columns)
    {
        columnNames.Add(column.ColumnName); 
    }

    builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");

    foreach (DataRow row in dataTable.Rows)
    {
        List<string> currentRow = new List<string>();

        foreach (DataColumn column in dataTable.Columns)
        {
            object item = row[column];

            currentRow.Add(item.ToString());
        }

        rows.Add(string.Join(",", currentRow.ToArray()));
    }

    builder.Append(string.Join("\n", rows.ToArray()));

    Response.Clear();
    Response.ContentType = "text/csv";
    Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
    Response.Write(builder.ToString());
    Response.End();
}

当我运行它时,浏览器会提示我保存 CSV 文件。

编辑:

如果您想保持当前的方法(生成 HTML,而不是 CSV),请尝试以下操作:

Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.xls");

请注意,我只是将文件扩展名从 CSV 更改为 XLS。使用 CSV 扩展时,文本在 Excel 中显示为 HTML。使用 XLS,它看起来就像上面的行被注释掉时一样。

于 2012-11-06T06:02:57.800 回答
3

与 NickW 的解决方案相同,但更简洁地使用 LINQ:

//Append column names
builder.Append(String.Join(",", 
    from DataColumn c in dataTable.Columns
    select c.ColumnName
)).Append("\n");

//Append data from datatable
builder.Append(string.Join("\n", 
    from DataRow row in dataTable.Rows
    select String.Join("\n", 
        String.Join(",", row.ItemArray)
    )
));

Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
Response.Write(builder.ToString());
Response.End();
于 2012-11-06T09:53:56.423 回答
1

最后我想我明白了,如果我们打算在 asp.net 页面上生成 excel 文件,我们需要编写一个 http 处理程序,现在我的 button_click 只是重定向到 TestHandler.ashx 页面并呈现 excel 文件。:)

非常感谢你们所有人

public class TestHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        StringWriter textWriter = new StringWriter();
        Html32TextWriter htmlTextWriter = new Html32TextWriter(textWriter);
        DataGrid dg = new DataGrid();
        dg.DataSource = GetData();

        //Get the html for the control
        dg.EnableViewState = false;
        dg.DataBind();
        dg.RenderControl(htmlTextWriter);

        //Write the HTML back to the browser.
        context.Response.Clear();

        //context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=test.csv"));
        //context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=abc.xls"));
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.Write(textWriter.ToString());
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
于 2012-11-06T20:39:06.300 回答
0

尝试改变这个:

Response.ContentType = "application/text";

或者

Response.ContentType = "text/csv";
于 2012-11-06T05:54:27.870 回答