导出到Excel乱码的问题.
环境: Windows 2003 Server英文版,Sql2005英文版, .Net 1.0(C#)
问题: 将数据库里的数据导出到Excel中时,非英文字符出现乱码. 在数据库中显示正常.
我们的系统有很多种语言,如何才能将非英文字符导出到Excel中而不出现乱码?
部分代码如下:
C# code
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.AddHeader( "Content-Disposition", "attachment;filename="+filename);
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
//byte[] array1 = new byte[] {0xFF, 0xFE };
byte[] array1 = new byte[] {0xEF, 0xBF, 0xBE};
Response.BinaryWrite(array1);
System.Web.HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content='text/html; charset=utf-8'>");
String s;
s = "<P>おはようございます?????Здравствуте</P>";
// byte[] converted = System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString());
// Response.BinaryWrite(converted);
Response.Write(s);
Response.Flush();
Response.End();
求高手帮助.谢谢.
------解决方案--------------------但是一试,便出现了乱码,解决方案如下
public static void Export(System.Web.UI.Page page, System.Web.UI.Control dg, string fileName, string typeName)
{
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("GB2312");
httpResponse.ContentType = typeName;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dg.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();
}
public 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