在ASP.Net中生成CSV文件

时间:2012-11-06 05:22:50

标签: c# asp.net excel file csv

我在按钮点击事件的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 个答案:

答案 0 :(得分:17)

我不确定你的目标是什么,所以我假设你想在按钮点击事件中创建一个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,就像上面的行被注释掉一样。

答案 1 :(得分: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();

答案 2 :(得分: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;
        }
    }
}

答案 3 :(得分:0)

尝试更改此内容:

Response.ContentType = "application/text";

或者

Response.ContentType = "text/csv";