编码问题

时间:2010-08-31 15:10:39

标签: c#-3.0

我想将数据从DaraGrid导出到Excel文件中。用法语提供这些数据 在这里,你是我的方法:

public static void ExportGridView( DataGrid dataGrid, string fileName)
    {
        HttpResponse m_Response = HttpContext.Current.Response;
        m_Response.Clear();
        m_Response.AddHeader("content-disposition",
            string.Format("attachment;filename={0}", fileName));
        m_Response.Charset = "";           
        m_Response.ContentType = "application/octet-stream"; //"application/vnd.xls";
        m_Response.ContentEncoding = Encoding.UTF32;
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        dataGrid.RenderControl(htmlWrite);
        m_Response.Write(stringWrite.ToString());
        m_Response.End();

}

否则输出不是好的法语格式

前)

Engagé=> engagé

Société=> SociéTA©

3 个答案:

答案 0 :(得分:6)

尝试使用ISO-8859-1

public static void ExportGridView(DataGrid dataGrid, string fileName)
{
    var response = HttpContext.Current.Response;
    response.Clear();
    response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
    var isoEncoding = Encoding.GetEncoding("iso-8859-1");
    response.Charset = isoEncoding.WebName;
    response.ContentType = "application/vnd.ms-excel";
    response.ContentEncoding = isoEncoding;
    using (var writer = new StringWriter())
    using (var htmlWriter = new HtmlTextWriter(writer))
    {
        dataGrid.RenderControl(htmlWriter);
        response.Write(writer.GetStringBuilder().ToString());
    }
    response.End();
}

另一个替代方案,可能更好的是生成一个完整的HTML页面并指定恕我直言更好的UTF8编码:

public static void ExportGridView(DataGrid dataGrid, string fileName)
{
    var response = HttpContext.Current.Response;
    response.Clear();
    response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
    response.Charset = Encoding.UTF8.WebName;
    response.ContentType = "application/vnd.ms-excel";
    response.ContentEncoding = Encoding.UTF8;
    using (var writer = new StringWriter())
    using (var htmlWriter = new HtmlTextWriter(writer))
    {
        dataGrid.RenderControl(htmlWriter);
        string html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>Test</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>{0}</body></html>";
        response.Write(string.Format(html, writer.GetStringBuilder()));
    }
    response.End();
}

答案 1 :(得分:0)

将内容编码设置为UTF8应确保正确解释Excel文件中的特殊符号。当然,您需要确保在安装的客户端计算机上安装了法语字体。

答案 2 :(得分:0)

我怀疑他/她是出于某种原因使用utf32。我很想完全触及那条线,看看会发生什么。如果从Excel到DataGrid,utf8会工作我认为你就在那里,但它是另一种方式。这条线甚至可能不是问题。

我对那些“StringWriter”对象更加怀疑。我不熟悉那些。如果您使用html来移动东西,浏览器不应该能够识别utf32,而是将它视为utf16,这可能是您的问题。