您的位置:首页 > 其它

导出EXCEL,PDF 方法简单明了

2015-08-05 17:08 239 查看
在接触项目的时候,往往有时候我们会遇到导出一些有格式的文档,下面我就简单介绍导出出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来做)

[b]
[/b]

首先创建一个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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: