导出EXCEL出问题了

xxzjzb1 2009-05-13 12:05:35
源代码:(导出Gridview中的值)
GridView GridView2 = new GridView();
GridView2.DataSource = (DataView)Session["dvlist9"];
GridView2.DataBind();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView2.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
运行没问题,但是导出的Excel非真正的Excel(用.txt打开不是乱码),所如导出的Excel不能导入,怎样控制源代码,可以生成真正的Excel?(看过不少解答,但是没有源代码,只是偏方,不能根上治病,给个c#源代码吧,初学者)
...全文
85 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
LGP88864237 2009-05-13
  • 打赏
  • 举报
回复
我刚做个项目用到了,用我这个方法就可以了,绝对可以。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace Public
{
public static class ToExcel
{
//将GridView数据导出至Excel中

public static string GridViewToExcel(GridView gd, string strPath, string strFileName)
{


new Help().CreateFolder(@"C:\reportforms");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gd.RenderControl(htw);
string strHtml = sw.ToString().Trim();
string ExcelFileName = strFileName;
string FilePhysicialPathName = strPath; //Request.PhysicalApplicationPath;

//生成的Excel文件名

string objectExcelFileName = Path.Combine(FilePhysicialPathName, ExcelFileName);
if (File.Exists(objectExcelFileName))
{
File.Delete(objectExcelFileName);
}
FileStream fs = new FileStream(objectExcelFileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs, Encoding.GetEncoding("GB18030"));
bw.Write(strHtml);
bw.Close();
fs.Close();


return "";


}
}
}

gyouyang 2009-05-13
  • 打赏
  • 举报
回复
板凳
LGP88864237 2009-05-13
  • 打赏
  • 举报
回复
using System.Linq;
你去掉就行了,我用的是VS2008.

new Help().CreateFolder(@"C:\reportforms");
是我写的一个类,就是如果没该文件夹就创建,要是有的话就不动。你不要也可以
LGP88864237 2009-05-13
  • 打赏
  • 举报
回复
你文件的后缀名一定要是“报警信息报表.xls”,类似这样的才行的,这样肯定可以了,给分吧,呵呵

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧