导出EXCEL,PDF 方法简单明了

在接触项目的时候,往往有时候我们会遇到导出一些有格式的文档,下面我就简单介绍导出出EXCEL,PDF WORD,方法很简单。没那么一堆堆Code看起来那么烦躁。

  // 导出EXCEL

  void Export()
    {

        string ds = Request["ds"];//接收参数
        string de = Request["de"];//接收参数



        if (ds .IsNotNull()&&de.IsNotNull())//参数不为空的时候
        {
            DataSet dataset = BLL.GETREPORT(regionId, ds, de);//这里我写了一个方法是用 DataSet把数据库的表数据读出来的,你们可以按照你们方法。
            if (dataset.IsNotNull())//读出数据如果不为空的话
            {
                string fileName = "Time(" + ds + "To" + de + ").xlsx";//这个是导出Excel的名称
                string path = Server.MapPath("~/Excel/");
                if (ExportExcel.ExportToExcel(dataset.Tables[0], path, fileName, null))
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);     //设置回发内容为Excel
                    Response.ContentType = "application/ms-excel";
                    Response.WriteFile(path + fileName);                            //把刚刚生成的Excel文件写入Http流
                    Response.End();
                }
            }
        }
    }

上面这段代码就是导出Excel,只要你下载个Excel包即可的了。


  // 导出PDF(用wkhtmltopdf.exe来做)


首先创建一个pdf.aspx文件

   void OutPdf()
    {
        //因为Web 是多线程环境,避免甲产生的文件被乙下载去,所以档名都用唯一 
        string fileNameWithOutExtention = Guid.NewGuid().ToString();
        fileNameWithOutExtention = Request["ds"] ;
        fileNameWithOutExtention = HttpUtility.UrlEncode(fileNameWithOutExtention, System.Text.Encoding.UTF8);
       id = Request["ds"];
       id = HttpUtility.UrlEncode(id, System.Text.Encoding.UTF8);
       string times = DateTime.Now.ToString("yyyyMMddHHmmss");

       Process p = System.Diagnostics.Process.Start(@"E:\yk\pdf\wkhtmltopdf.exe", //这个是放 wkhtmltopdf.exe @"http://192.168.221.29:8018/Report/pdfdetail.aspx?ds=" + id + @" E:\yk\pdf\pdf\" + times + ".pdf");//pdfdetail.aspx另外一个设计导出pdf页面内容
        p.WaitForExit();

        //把文件读进文件流 
        FileStream fs = new FileStream(@"E:\yk\pdf\pdf\" + times + ".pdf", FileMode.Open);
        byte[] file = new byte[fs.Length];
        fs.Read(file, 0, file.Length);
        fs.Close();
        //Response给客户端下载 
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=" + times + ".pdf");//强制下载 
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(file);
    }

然后创建一个dfdetail.aspx文件

在这个页面设计你要导出的pdf格式即可。简单吧!

不懂可以问我http://www.pomeloit.com/




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值