今天怎麼有客戶反應導出的Excel的亂碼,??!!我記得我測試過的啊,後來我用服務器上的再測了下,確實有的會亂碼有的卻不會,真是奇怪,後來改它的編碼utf-8 big5 都試了,就是不行,網上找了一個遇到同樣問題的朋友的解決方案,確實可行!!不錯,謝謝
被注釋的是我之前用的,不好的方法,
private void BtnPushExcel_Click(object sender, System.EventArgs e)
...{
string fileName = "Excel.xls";
Export(this.DataGrid1,fileName);
// HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8));
// HttpContext.Current.Response.Charset ="UTF-8";
// //HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("BIG5");
// HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("BIG5");
// HttpContext.Current.Response.ContentType ="application/ms-Excel";
// Datagrid2.Page.EnableVIEwState =false;
// System.IO.StringWriter tw = new System.IO.StringWriter() ;
// System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
// this.DataGrid1.RenderControl(hw);
// HttpContext.Current.Response.Write(tw.ToString());
// HttpContext.Current.Response.End();
}
private void Export(System.Web.UI.WebControls.DataGrid dg,string fileName)
{
System.Web.HttpResponse httpResponse = Page.Response;
httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8));
httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("BIG5");
httpResponse.ContentType ="application/ms-Excel";
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
dg.RenderControl(hw);
string filePath = 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 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=BIG5");
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;
}
}