日期:2014-05-18  浏览次数:20388 次

被上面催的急 新手求助大家 如何把gridview导到excel后存在服务器
新手刚接触.net,现在需要把GridView的内容存在excel后保存在服务器指定位置,在网上找到了ToExcel函数,实现了将GridView的内容复制到excel,提示将excel保存到客户端,会有小框 【打开】【保存】【取消】,怎么能实现将excel保存在服务器项目目录呢? 改的代码有问题,新手求指教,求帮助啊。

C# code

private void ToExcel(Control ctl)
{    
  string FileName = "z.xls";
  HttpContext.Current.Response.Charset = "UTF-8";
  HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
  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());
  //到这里将gridview保存到excel表z.xls了, 执行HttpContext.Current.Response.End()后提示将excel保存到客户端,
  //会有小框 【打开】【保存】【取消】,可是怎么将表存到服务器呢?我在后面加了SaveAs代码有问题啊!
  HttpFileCollection files = HttpContext.Current.Request.Files;
  System.Web.HttpPostedFile myFile = files[FileName];
  string ppath =  @"D:/excel/"+ FileName ;
  myFile.SaveAs(ppath);//保存上载文件的内容。
  // 这里报错未将对象引用设置到对象的实例。感觉是System.Web.HttpPostedFile myFile = files[FileName];这句的问题,怎么找到gridview保存后的excel文件z.xls保存在服务器上呢?
  HttpContext.Current.Response.End();
  }



------解决方案--------------------
保存方法
string ppath = @"D:/excel/"+ FileName ;
System.IO.File.WriteAllText(ppath,tw.ToString());
HttpContext.Current.Response.Write(tw.ToString());

------解决方案--------------------
这个要在

string FileName = "z.xls";
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
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);


这段代码里可以设置 具体的去Google吧