读书人

ASP.NET 导出Excel后 打开Excel资料发

发布时间: 2013-08-11 22:22:29 作者: rapoo

ASP.NET 导出Excel后 打开Excel文件发现是乱码
大家好:最近根据需求 要我们做一个ASP.NET的导出EXCEL ,我在网上借鉴了一段代码,但是用在我这里 ,导出后打开EXCEL发现很多都是乱码 我勒个去!求各位大神们 帮忙看看 这代码哪里有问题:

以下是导出功能的代码:
public static void ExportToSpreadsheet(DataTable table, string name)
{
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=" + name + 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();

}
导出后的Excel文件如图: (乱码)

ASP.NET 导出Excel后 打开Excel资料发现是乱码


Excel ASP.NET 乱码 导出Excel
[解决办法]
出现乱码,一般都是编码造成的,这样改下看下:
curContext.Response.ContentType = "application/vnd.ms-excel";
03.curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
04.curContext.Response.Charset = "gb2312";
......
curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" + strWriter.ToString());
[解决办法]

curContext.Response.ContentType = "application/ms-excel"
这玩意这样搞
[解决办法]
Refer this:
http://www.cnblogs.com/insus/articles/1400266.html
http://www.cnblogs.com/insus/archive/2013/01/16/2862121.html
[解决办法]
Excel导出的一般是HTML格式,遇到2007以上高版本的就会容易出现乱码等现象,我一般采用的办法是生成Table,然后再导出CSV格式,或者通过XML弄成固定的模板再导出Excel。具体方法可参照网上实例!

读书人网 >asp.net

热点推荐