我在做gridview导出excel,我是引用别人的方法,别人的都正常,我下载后的就是乱码,可穿进去的时候显示是正常的,请问应该在哪儿修改一下呢?
/// <summary>
/// 导出成Excel
/// </summary>
/// <param name="page">要导出的页面.如:this.Page</param>
/// <param name="tab">包含数据的DataTable</param>
/// <param name="FileName">要保存的文件名,如test.xls</param>
public static void Export(System.Web.UI.Page page, System.Data.DataTable tab, string FileName)
{
System.Web.HttpResponse httpResponse = page.Response;
System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid();
dataGrid.DataSource = tab.DefaultView;
dataGrid.AllowPaging = false;
dataGrid.HeaderStyle.BackColor = System.Drawing.Color.Transparent;
dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
dataGrid.HeaderStyle.Font.Bold = true;
dataGrid.DataBind();
httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)); //filename="*.xls";
httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8") ;
httpResponse.ContentType = "application/ms-excel";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dataGrid.RenderControl(hw);
string filePath = page.Server.MapPath("..") + "\\" + FileName;
System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
sw.Write(tw.ToString());
sw.Close();
DownFile(httpResponse, FileName, filePath);
httpResponse.End();
}
private static bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)
{
try
{
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
long fLen = fs.Length;
int size = 102400;//每100K同时下载数据
byte[] readData = new byte[size];//指定缓冲区的大小
if (size > fLen) size = Convert.ToInt32(fLen);
long fPos = 0;
bool isEnd = false;
while (!isEnd)
{
if ((fPos + size) > fLen)
{
size = Convert.ToInt32(fLen - fPos);
readData = new byte[size];
isEnd = true;
}
fs.Read(readData, 0, size);//读入一个压缩块
Response.BinaryWrite(readData);
fPos += size;
}
fs.Close();
System.IO.File.Delete(fullPath);
return true;
}
catch
{
return false;
}
}