#region
/// <summary>
/// 生成Excel文件
/// </summary>
/// <param name="ds">数据集</param>
/// <param name="fileName">生成文件名</param>
public void CreateExcel(DataTable dt, string fileName,Page page)
{
HttpResponse resp;
resp = page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
string colHeaders = "", ls_item = "";
////定义表对象与行对象,同时用DataSet对其值进行初始化
//DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item +=row[i].ToString() + "\n";
}
else
{
ls_item +=row[i].ToString() + "\t";
}
}
resp.Write(ls_item);
ls_item = "";
}
resp.End();
}
#endregion
17 个解决方案
#1
编码问题!
#2
楼主用红色语句替换原来那句试试看
#3
1.设置web.config文件。
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
2.传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name));
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
3.如果是从 .HTML 文件向 .Aspx 文件进行传递中文参数的话(即不从后台用 Redirect()方法进行 Url 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
<script language="JavaScript">
function GoUrl()
{
var Name = "中文参数";
location.href = "B.aspx?Name="+escape(Name);
}
</script>
<body onclick="GoUrl()">
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
2.传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name));
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
3.如果是从 .HTML 文件向 .Aspx 文件进行传递中文参数的话(即不从后台用 Redirect()方法进行 Url 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
<script language="JavaScript">
function GoUrl()
{
var Name = "中文参数";
location.href = "B.aspx?Name="+escape(Name);
}
</script>
<body onclick="GoUrl()">
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
#4
up
#5
我也出现过
我的是如果换成UTF-8的话 就把源码倒出来了
我的是如果换成UTF-8的话 就把源码倒出来了
#6
我改成utf8就变成这样了
搴忓彿 鏈哄櫒鐮?娑堣垂鍦烘墍 鍦版柟娑堣垂ID 浼氬憳鍗″彿 浼氬憳濮撳悕 娑堣垂绫诲瀷 娑堣垂閲戦 鍓╀綑閲戦 娑堣垂鏃堕棿 澶囨敞
#7
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB18030");
#8
Gridview导出为Excel
尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。总结了一下应该注意下面几点:
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )
的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:
修改你的aspx文件中的:
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.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 false;
}
}
怎么调用?? 其实就是怎么调用Export这个函数罢了.
以上方法可以很有效地解决导出的乱码问题
http://blog.xunbin.com/Article/22.aspx
尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。总结了一下应该注意下面几点:
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )
的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:
修改你的aspx文件中的:
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.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 false;
}
}
怎么调用?? 其实就是怎么调用Export这个函数罢了.
以上方法可以很有效地解决导出的乱码问题
http://blog.xunbin.com/Article/22.aspx
#9
web.config
<globalization requestEncoding=" utf-8" responseEncoding=" utf-8"/>
该成 gb2312
<globalization requestEncoding=" utf-8" responseEncoding=" utf-8"/>
该成 gb2312
#10
这个很好,很强大哦.
#11
这个很好,很强大哦.
#12
我改成这个了,可是对方在那导出的 Excel还是乱码``!!`
#13
先把你的EXCEL设置 文本格式
然后
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
config里也配置一下
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
然后
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
config里也配置一下
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
#14
我已经这么做过配置了,不行`~~~~
#15
1页面: <head>
<meta content='text/html; charset=gb2312' http-equiv='content-type' />
<title>无标题页</title>
</head>
2代码: protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("content-disposition", "inline;filename=\"" + System.Web.HttpUtility.UrlEncode("中文名称", System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentType = "application/ms-excel";
}
<meta content='text/html; charset=gb2312' http-equiv='content-type' />
<title>无标题页</title>
</head>
2代码: protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("content-disposition", "inline;filename=\"" + System.Web.HttpUtility.UrlEncode("中文名称", System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentType = "application/ms-excel";
}
#16
算了 全都给你吧 剩余部分
页面:<body>
<form id="form1" runat="server">
<div>
<table border="1" style=" border-bottom-color:Black">
<tr>
<td>中文</td>
<td style="width: 45px">Title</td>
</tr>
<%=db()%>
</table>
</div>
</form>
</body>
代码:
public string db()
{
string strJava = "";
// StringBuilder strSql = new StringBuilder();
ArticleManage am= new ArticleManage();
List<Article> list = am.GetAllArticle("0");
strJava += string.Format("<tr><td>中文阿百川</td><td >中文</td></tr>");
foreach(Article a in list)
{
strJava += string.Format("<tr><td>{0}</td><td >{1}</td></tr>", a.ArticleId, a.TopDate);
}
return strJava;
}
页面:<body>
<form id="form1" runat="server">
<div>
<table border="1" style=" border-bottom-color:Black">
<tr>
<td>中文</td>
<td style="width: 45px">Title</td>
</tr>
<%=db()%>
</table>
</div>
</form>
</body>
代码:
public string db()
{
string strJava = "";
// StringBuilder strSql = new StringBuilder();
ArticleManage am= new ArticleManage();
List<Article> list = am.GetAllArticle("0");
strJava += string.Format("<tr><td>中文阿百川</td><td >中文</td></tr>");
foreach(Article a in list)
{
strJava += string.Format("<tr><td>{0}</td><td >{1}</td></tr>", a.ArticleId, a.TopDate);
}
return strJava;
}
#17
//用这个代码试试
private void Export(System.Web.UI.WebControls.DataGrid 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 = 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=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;
}
}
}
#1
编码问题!
#2
楼主用红色语句替换原来那句试试看
#3
1.设置web.config文件。
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
2.传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name));
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
3.如果是从 .HTML 文件向 .Aspx 文件进行传递中文参数的话(即不从后台用 Redirect()方法进行 Url 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
<script language="JavaScript">
function GoUrl()
{
var Name = "中文参数";
location.href = "B.aspx?Name="+escape(Name);
}
</script>
<body onclick="GoUrl()">
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
2.传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name));
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
3.如果是从 .HTML 文件向 .Aspx 文件进行传递中文参数的话(即不从后台用 Redirect()方法进行 Url 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
<script language="JavaScript">
function GoUrl()
{
var Name = "中文参数";
location.href = "B.aspx?Name="+escape(Name);
}
</script>
<body onclick="GoUrl()">
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));
#4
up
#5
我也出现过
我的是如果换成UTF-8的话 就把源码倒出来了
我的是如果换成UTF-8的话 就把源码倒出来了
#6
我改成utf8就变成这样了
搴忓彿 鏈哄櫒鐮?娑堣垂鍦烘墍 鍦版柟娑堣垂ID 浼氬憳鍗″彿 浼氬憳濮撳悕 娑堣垂绫诲瀷 娑堣垂閲戦 鍓╀綑閲戦 娑堣垂鏃堕棿 澶囨敞
#7
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB18030");
#8
Gridview导出为Excel
尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。总结了一下应该注意下面几点:
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )
的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:
修改你的aspx文件中的:
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.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 false;
}
}
怎么调用?? 其实就是怎么调用Export这个函数罢了.
以上方法可以很有效地解决导出的乱码问题
http://blog.xunbin.com/Article/22.aspx
尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。总结了一下应该注意下面几点:
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET 服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )
的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:
修改你的aspx文件中的:
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="SysUser.aspx.cs" Inherits="Autho_SysUser2" %>
增加红色的部分就ok了。
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.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 false;
}
}
怎么调用?? 其实就是怎么调用Export这个函数罢了.
以上方法可以很有效地解决导出的乱码问题
http://blog.xunbin.com/Article/22.aspx
#9
web.config
<globalization requestEncoding=" utf-8" responseEncoding=" utf-8"/>
该成 gb2312
<globalization requestEncoding=" utf-8" responseEncoding=" utf-8"/>
该成 gb2312
#10
这个很好,很强大哦.
#11
这个很好,很强大哦.
#12
我改成这个了,可是对方在那导出的 Excel还是乱码``!!`
#13
先把你的EXCEL设置 文本格式
然后
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
config里也配置一下
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
然后
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
config里也配置一下
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
#14
我已经这么做过配置了,不行`~~~~
#15
1页面: <head>
<meta content='text/html; charset=gb2312' http-equiv='content-type' />
<title>无标题页</title>
</head>
2代码: protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("content-disposition", "inline;filename=\"" + System.Web.HttpUtility.UrlEncode("中文名称", System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentType = "application/ms-excel";
}
<meta content='text/html; charset=gb2312' http-equiv='content-type' />
<title>无标题页</title>
</head>
2代码: protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("content-disposition", "inline;filename=\"" + System.Web.HttpUtility.UrlEncode("中文名称", System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentType = "application/ms-excel";
}
#16
算了 全都给你吧 剩余部分
页面:<body>
<form id="form1" runat="server">
<div>
<table border="1" style=" border-bottom-color:Black">
<tr>
<td>中文</td>
<td style="width: 45px">Title</td>
</tr>
<%=db()%>
</table>
</div>
</form>
</body>
代码:
public string db()
{
string strJava = "";
// StringBuilder strSql = new StringBuilder();
ArticleManage am= new ArticleManage();
List<Article> list = am.GetAllArticle("0");
strJava += string.Format("<tr><td>中文阿百川</td><td >中文</td></tr>");
foreach(Article a in list)
{
strJava += string.Format("<tr><td>{0}</td><td >{1}</td></tr>", a.ArticleId, a.TopDate);
}
return strJava;
}
页面:<body>
<form id="form1" runat="server">
<div>
<table border="1" style=" border-bottom-color:Black">
<tr>
<td>中文</td>
<td style="width: 45px">Title</td>
</tr>
<%=db()%>
</table>
</div>
</form>
</body>
代码:
public string db()
{
string strJava = "";
// StringBuilder strSql = new StringBuilder();
ArticleManage am= new ArticleManage();
List<Article> list = am.GetAllArticle("0");
strJava += string.Format("<tr><td>中文阿百川</td><td >中文</td></tr>");
foreach(Article a in list)
{
strJava += string.Format("<tr><td>{0}</td><td >{1}</td></tr>", a.ArticleId, a.TopDate);
}
return strJava;
}
#17
//用这个代码试试
private void Export(System.Web.UI.WebControls.DataGrid 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 = 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=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;
}
}
}