从C#导出xls文件 - 不保存特殊字母

时间:2012-11-06 15:53:13

标签: c# asp.net

我的网站asp.net(C#)导出.xls文件的功能有问题 它将所有<tr>保存到一个字符串中。 功能很好,但它没有正确保存波兰字符(Ł,ó, - 等) 我该如何解决这个问题?

这是我的代码:

string ExcelExport;
string StringExport;


 (..)

protected void lvUsers_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item is ListViewDataItem)
    {
        (..)

        StringExport = StringExport + string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>", currentUser.name, currentUser.surname, tel, currentUser.email);
    }
}




protected void btnDownloadList_Click(object sender, EventArgs e)
{
    ExcelExport = "<table><tr><td>Name</td><td>Surname</td><td>Telephone</td><td>E-mail</td></tr><tr><td> </td><td> </td><td> </td><td> </td></tr>" + StringExport + "</table>";

    Response.AddHeader("Content-disposition", "attachment; filename=raport.xls");
    Response.Charset = "utf-8";
    Response.ContentType = "application/ms-excel";
    Response.Write(ExcelExport);
    Response.End();

}

2 个答案:

答案 0 :(得分:2)

尝试使用此byte order mark (BOM)

中建议的similar solution
protected void btnDownloadList_Click(object sender, EventArgs e)
{
    ExcelExport = "<table><tr><td>Name</td><td>Surname</td><td>Telephone</td><td>E-mail</td></tr><tr><td> </td><td> </td><td> </td><td> </td></tr>" + StringExport + "</table>";

    Response.AddHeader("Content-disposition", "attachment; filename=raport.xls");
    Response.ContentType = "application/ms-excel";
    byte[] BOM = { 0xEF, 0xBB, 0xBF }; // The BOM for UTF-8 encoding.
    Response.BinaryWrite(BOM);
    Response.Write(ExcelExport);
    Response.End();

}

答案 1 :(得分:1)

utf-8字符集不包含波兰字符。快速搜索显示ISO 8859-2确实如此。我会尝试更改Charset并查看是否可以解决您的问题。