.net数据导出到excel【Update20111009】

     昨天临时要做一个把dataset中的数据导出到excel的功能,同事给了一段代码,功能实现,现分享:

在网上又看到一篇更全面的文章,分享地址:http://www.cnblogs.com/xiaotao823/archive/2008/09/26/1299364.html

现在常用的方式是参考:http://excelpackage.codeplex.com/

 实例方法:

  string sql = string.Format("select * from ...{0}}", SearchTerms);
            string name = "Search" + System.DateTime.Now.ToString("yyMMddHHmmss") + ".xlsx";//文件名
            DataTable dt = Biz.csFormDateReport(sql);//数据源
            FileInfo template = new FileInfo(Server.MapPath("/Controls/CustomerService/Report/TemplateExcel/MonthFormTemplate.xlsx"));//模板文件
            if (dt.Rows.Count > 0)
            {
              if (!template.Exists) throw new Exception("Template file does not exist!");
              using (ExcelPackage pck = new ExcelPackage(template, true))
              {
                  ExcelWorksheet ws = pck.Workbook.Worksheets["FormList"];
                  if (ws != null)
                  {
                      const int startRow = 3;//开始插入数据的行
                      int row = startRow;
                      foreach (DataRow dr in dt.Rows)
                      {
                          //产品名称	工单属性	类别	结案	未结案	详细描述	个案总结
                          if (row > startRow) ws.InsertRow(row, 1);
                          ws.Cells[row, 1].Value = dr["ProjectName"].ToString();
                          ........//填充数据    row++;
                      }
                      //delete the two spare rows we have in the template 
                      ws.DeleteRow(row, 1);
                      row--;

                      ws.Cells[row + 1, 4].CreateArrayFormula("=SUM(D" + startRow + ":D" + row + ")");//添加计算公式
                      ws.Cells[row + 1, 5].CreateArrayFormula("=SUM(E" + startRow + ":E" + row + ")");

                      Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                      Response.ContentType = "Application/vnd.ms-Excel";
                      Response.AddHeader("content-disposition", "attachment;  filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8) + "");
                      Response.BinaryWrite(pck.GetAsByteArray());
                      Response.End();
                  }
              }
            }
            else
            { this.labInfo.Text = "无数据!"; return; }


Excel模板,合计总计会自动计算出来!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值