.net中导出Excel

1.GridView中数据导出到Excel
public override void VerifyRenderingInServerForm(Control control)
{
}
 public void ExcelOut(GridView gv)
    {
       if (gv.Rows.Count > 0)
       {
           stringdeskPath =System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
          Response.Clear();
          Response.ClearContent();
          Response.AddHeader("Content-Disposition", "attachment;filename="考勤记录.xls");
          Response.ContentEncoding =System.Text.Encoding.GetEncoding("GB2312");
          Response.ContentType = "application/ms-excel";
          StringWriter sw = new StringWriter();
          HtmlTextWriter htw = new HtmlTextWriter(sw);
          gv.RenderControl(htw);
          Response.Write(sw.ToString());
          Response.Flush();
          Response.End();
       }
       else
       {
          Response.Write("没有数据");
       }
    }



2.Dataset中数据导出到Excel
   
  //建立Excel对象  
       HttpResponse resp;
       resp = Page.Response;
       resp.ContentEncoding =System.Text.Encoding.GetEncoding("GB2312");
       HttpBrowserCapabilities b =Request.Browser;
       if (b.Browser.ToString() == "IE")
       {
           stringfilename = year + "年房地产收费记录.xls";
          resp.AppendHeader("Content-Disposition", "attachment;filename=" +HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
       }
       else
       {
          resp.AppendHeader("Content-Disposition","attachment;filename="收费记录.xls");
       }
       resp.ContentType = "application/ms-excel";
       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();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值