日期:2014-05-17  浏览次数:20497 次

这个导出的文件名称怎么是乱码啊,内容又不是乱码
C# code
 private void CreateExcel(DataTable table, string fileName)
    {
        Random r = new Random();
        string rf = "";
        for (int j = 0; j < 10; j++)
        {
            rf = r.Next(int.MaxValue).ToString();
        }

        HttpContext context = HttpContext.Current;
        context.Response.Clear();

        context.Response.ContentType = "text/csv";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + rf + ".xls");
        context.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

        foreach (DataColumn column in table.Columns)
        {
            context.Response.Write(column.ColumnName + ",");
            //context.Response.Write(column.ColumnName + "(" + column.DataType + "),");  
        }

        context.Response.Write(Environment.NewLine);
        double test;

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                switch (table.Columns[i].DataType.ToString())
                {
                    case "System.String":
                        if (double.TryParse(row[i].ToString(), out test)) context.Response.Write("=");
                        context.Response.Write("\"" + row[i].ToString().Replace("\"", "\"\"") + "\",");
                        break;
                    case "System.DateTime":
                        if (row[i].ToString() != "")
                            context.Response.Write("\"" + ((DateTime)row[i]).ToString("yyyy-MM-dd hh:mm:ss") + "\",");
                        else
                            context.Response.Write("\"" + row[i].ToString().Replace("\"", "\"\"") + "\",");
                        break;
                    default:
                        context.Response.Write("\"" + row[i].ToString().Replace("\"", "\"\"") + "\",");
                        break;
                }
            }
            context.Response.Write(Environment.NewLine);
        }

        context.Response.End();
    }

这是一个DataTable 导出 Excel 的方法

------解决方案--------------------
context.Response.Charset = "GB2312";

context.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(ExcelFileName,System.Text.Encoding.UTF8) + ".xls"); 

context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
context.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 

System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);
------解决方案--------------------
Response.headerEncoding =System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(ExcelFileName,System.Text.Encoding.UTF8) + ".xls"); 

如果你是 网页

HttpUtility.UrlEncode 可以改成 server.UrlEncode ,如果你的网页编码就是utf8 后面编码格式可以省略