iText导出pdf,poi导出excel并下载到客户端

项目中需要做导出功能,要支持excel,pdf导出。

excel导出我选择使用poi;pdf导出我选择使用iText,在此单独做记录。

先说说在设计与开发中的问题,从整体上把握设计思路。

思路(一)

在页面json拼装数据,在后台导出pdf文件到客户端。

本例子只是简单的导出列表数据,没有涉及到图片等其他复杂格式文件。所以还是比较简单的。

这个设计思路是最理想的。

在后台获取前台数据,把这些数据直接生成pdf文件流输出到response中去,

不会在服务器留下垃圾文件。在客户端会弹出文件保存框,直接保存到客户端本地。

-------------------

这个思路很好,但是在导出到客户端时我遇到问题,就是弹不出文件保存框,页面没什么反应。用ajax回调函数

弹出返回数据是一堆乱码。

基于此原因,我改用

思路(二)

把pdf文件生成在服务器下的一个目录下,在ajax回调函数中使用这个拼装成访问路径,

这样可以下载文件。如果浏览器总是弹出阻止下载文件的弹出提示,可以在浏览器工具--internet 选项--

安全--自定义级别--下载,改一下:文件下载:启用;文件下载的自动提示:启用。都是启用就可以了,

这样就不会在弹出了。

 

这样也有问题,1会在服务器下生成许多垃圾文件,需要维护人员定期的删除,不然硬盘就不够用了。

2在客户端访问生成的文件会是zip文件或者是没有后缀的文件格式,或者直接在浏览器直接打开了。

如果是zip或者是其他格式不被浏览器识别,解决问题的方法就是在web.xml中设置mime类型。

这个就不细说了,网上一大堆。如果直接在浏览器打开pdf文件,那可以在你电脑安装的pdf阅读器设置里

把在浏览器中打开这一项去掉。

这样还是会有问题:

1,web.xml设置的mime类型对整个工程都是有效地,在这里我想让浏览器下载这个类型的文件而不是打开,所以

我设置了mime;而在其他地方就是需要浏览器打开这个类型的文件提供在线阅读,而不是弹出下载的文件选择框。

所以设置mime类型是会发生冲突的。

2,在pdf阅读器设置取消掉“在浏览器打开”这一项不太符合用户习惯,用户使用这个功能还需要设置自己电脑上的其他

软件,这个太不合理了。

 

这样的问题,我决定改变访问方式,使用下载,而不是直接给文件在服务器的地址直接访问。

思路(三)

可以在服务器路径下生成pdf文件,对于访问方式采用下载方式,下载完成后再删除此文件。

这和思路(一)区别不是很大,之所以采用这种方式,是因为在设置文件类型时,

用代码设置response.setContentType("application/pdf");

response.addHeader("Content-Disposition","attachment;filename="+serfilename.trim());

serfilename是生成的临时pdf文件的名字,随机的,这两行代码必须在调用输入输出流之前,

因为只要一调用流往客户端写文件,就会弹出文件保存框,这两行代码还没走到,所以是无效的。

如果写在调用流之前,这个文件的名字是在调用流之后才生成的文件名。

 

所以,读写的逻辑自己定。

你的方法如果能封装OutpuStream,那就把response对象也传入你的方法中,并在调用流之前先调用这两行代码。

如果你的方法不能封装OutpuStream,那就先把文件写在服务器下路径,生成文件后,调用这两行代码,

然后自己再写读写文件到response。只要保证在读写流调用前就可以。

 

所以思路(三)和思路(一)是差不多的。

------------------

 总之,

1,在web.xml中不要设置mime,在程序中能控制的就不要在控制全局的web.xml中设置。

2,文件的访问最好用下载方式,不要直接贴个url做成链接。

3,不要在服务器下生成垃圾文件。临时的文件用过后要删除。最好别生成临时文件。

 -------------------

pdf导出我采用方式(三),生成临时文件,下载后删除。

excel导出我采用方式(一),直接写到客户端。

这是最后的代码,采用servlet方式。

web.xml  注意注释掉的部分

[html]  view plain copy
  1.     <servlet>  
  2.         <description>ExportExcelServletDescription</description>  
  3.         <display-name>ExportExcelServlet</display-name>  
  4.         <servlet-name>ExportExcelServlet</servlet-name>  
  5.         <servlet-class>org.hd.report.serv.ExportExcelServlet</servlet-class>  
  6.     </servlet>  
  7.       
  8.     <servlet-mapping>  
  9.         <servlet-name>ExportExcelServlet</servlet-name>  
  10.         <url-pattern>/ExportExcelServlet</url-pattern>  
  11.     </servlet-mapping>  
  12.       
  13.         <servlet>  
  14.         <description>ExportPdfServletDescription</description>  
  15.         <display-name>ExportPdfServlet</display-name>  
  16.         <servlet-name>ExportPdfServlet</servlet-name>  
  17.         <servlet-class>org.hd.report.serv.ExportPdfServlet</servlet-class>  
  18.     </servlet>  
  19.       
  20.     <servlet-mapping>  
  21.         <servlet-name>ExportPdfServlet</servlet-name>  
  22.         <url-pattern>/ExportPdfServlet</url-pattern>  
  23.     </servlet-mapping>  
  24.   
  25.   
  26.   
  27.   
  28.   
  29.       
  30. <!--   
  31.     <mime-mapping>  
  32.         <extension>doc</extension>  
  33.         <mime-type>application/msword</mime-type>  
  34.     </mime-mapping>  
  35.     <mime-mapping>  
  36.         <extension>docx</extension>  
  37.         <mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type>  
  38.     </mime-mapping>  
  39.   
  40.     <mime-mapping>  
  41.         <extension>xls</extension>  
  42.         <mime-type>application/msexcel</mime-type>  
  43.     </mime-mapping>  
  44.     <mime-mapping>  
  45.         <extension>xlsx</extension>  
  46.         <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>  
  47.     </mime-mapping>  
  48.       
  49.       
  50.     <mime-mapping>  
  51.         <extension>pdf</extension>  
  52.         <mime-type>application/pdf</mime-type>  
  53.     </mime-mapping>   
  54.       
  55.    -->  


pdf

[html]  view plain copy
  1. package org.hd.report.serv;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. import org.hd.util.ExportExcelUtil;  
  17. import org.hd.util.ExportPdfUtil;  
  18.   
  19. /**  
  20.  * Servlet implementation class PdfItextServlet  
  21.  */  
  22. public class ExportPdfServlet extends HttpServlet {  
  23.     private static final long serialVersionUID = 1L;  
  24.       
  25.     public ExportPdfServlet() {  
  26.         super();  
  27.     }  
  28.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  29.         doPost(request,response);  
  30.     }  
  31.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  32.         downLoadPdfService(request,response);  
  33.     }  
  34.       
  35.     protected void downLoadPdfService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  36.         request.setCharacterEncoding("UTF-8");  
  37.         response.setCharacterEncoding("UTF-8");  
  38. //      response.setContentType("text/xml");  
  39.           
  40.           
  41.         String thename = request.getParameter("dd") != null ? request.getParameter("dd") : "";  
  42.         String resjsonrequest.getParameter("resjson") != null ? request.getParameter("resjson").trim() : "";  
  43.         resjson=java.net.URLDecoder.decode(resjson,"UTF-8");  
  44.         System.out.println("resjson from page--"+resjson);  
  45.           
  46.         String clientFileName="";  
  47.         String pdfonserver=ExportPdfUtil.createPdfWithJson(resjson);  
  48.           
  49. //      String pdfonserverrequest.getParameter("pdfonserver") != null ? request.getParameter("pdfonserver") : "";  
  50.         pdfonserver=java.net.URLDecoder.decode(pdfonserver,"UTF-8");  
  51.         String serfilename=pdfonserver.substring(pdfonserver.lastIndexOf("/")+1);//xx.pdf  
  52.           
  53.         //如果是变生成文件,边写入输出流到servlet,客户端会在输出流写入的时候就弹出保存文件框,setContentType,addHeader所以必须在输出流之前调用。  
  54. //      response.setContentType("octets/stream");  
  55.         response.setContentType("application/pdf");  
  56. //      response.setContentType("application/x-msdownload");//对pdf这个也可以  
  57.           
  58.         response.addHeader("Content-Disposition","attachment;filename="+serfilename.trim());  
  59.           
  60.           
  61.         String wholeServerPath=ExportPdfUtil.TEMP_PDF_PATH+"\\"+serfilename;  
  62.         File fileOnServer=new File(wholeServerPath.trim());  
  63.         if(!fileOnServer.exists()){  
  64.             System.out.println("文件未找到。");  
  65.         }else{  
  66.             InputStream is=new BufferedInputStream(new FileInputStream(fileOnServer));  
  67.             OutputStream os=new BufferedOutputStream(response.getOutputStream());  
  68.             byte[] buf=new byte[1024];  
  69.             while((is.read(buf))!=-1){  
  70.                 os.write(buf);  
  71.                 os.flush();  
  72.             }  
  73.             if(os!=null){  
  74.                 os.flush();  
  75.                 os.close();  
  76.             }  
  77.             if(is!=null){  
  78.                 is.close();  
  79.             }  
  80.             if(fileOnServer.exists()){  
  81.                 boolean flag=fileOnServer.delete();  
  82.                 if(flag){  
  83.                     System.out.println(fileOnServer.getPath()+"完成删除。");  
  84.                 }  
  85.             }  
  86.         }  
  87.           
  88.     }  
  89.   
  90. }  


excel

[html]  view plain copy
  1. package org.hd.report.serv;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.hd.util.ExportExcelUtil;  
  12.   
  13. /**  
  14.  * Servlet implementation class PdfItextServlet  
  15.  */  
  16. public class ExportExcelServlet extends HttpServlet {  
  17.     private static final long serialVersionUID = 1L;  
  18.       
  19.     public ExportExcelServlet() {  
  20.         super();  
  21.     }  
  22.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  23.         doPost(request,response);  
  24.     }  
  25.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  26.         makeExcelService(request,response);  
  27.     }  
  28.       
  29.     protected void makeExcelService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  30.         request.setCharacterEncoding("UTF-8");  
  31.         response.setCharacterEncoding("UTF-8");  
  32.           
  33.           
  34.         String thename = request.getParameter("dd") != null ? request.getParameter("dd") : "";  
  35.         String resjsonrequest.getParameter("resjson") != null ? request.getParameter("resjson") : "";  
  36.         resjson=java.net.URLDecoder.decode(resjson,"UTF-8");  
  37.         System.out.println("servlet---resjson--"+resjson);  
  38.           
  39.   
  40.           
  41.         OutputStream os=response.getOutputStream();  
  42.           
  43.         String pdfonserver=ExportExcelUtil.exportExcelFromAllStr(resjson, null, os,response);  
  44.         pdfonserver=java.net.URLDecoder.decode(pdfonserver,"UTF-8");  
  45.         String serfilename=pdfonserver.substring(pdfonserver.lastIndexOf("/")+1);//xx.xlsx  
  46.           
  47.         //如果是变生成文件,边写入输出流到servlet,客户端会在输出流写入的时候就弹出保存文件框,setContentType,addHeader所以必须在输出流之前调用。  
  48.         //因为本例输出流已经封装到ExportExcelUtil的方法中,所以就把response传入,在方法内设置。  
  49. //      response.setContentType( "application/vnd.ms-excel");//2003  
  50. //      response.setContentType("application/ms-excel"); //2003  
  51. //      response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//2007  
  52.           
  53. //      response.setContentType("octets/stream");//压缩文件  
  54. //      response.setContentType("application/x-msdownload");//压缩文件  
  55. //      response.addHeader("Content-Disposition","attachment;filename="+serfilename.trim());  
  56. //      System.out.println(serfilename+"成功导出到客户端");  
  57.     }  
  58.   
  59. }  


核心代码,工具类:

pdf:

[html]  view plain copy
  1. /*  
  2.  * This class is part of the book "iText in Action - 2nd Edition"  
  3.  * written by Bruno Lowagie (ISBN: 9781935182610)  
  4.  * For more info, go to: http://itextpdf.com/examples/  
  5.  * This example only works with the AGPL version of iText.  
  6.  */  
  7.   
  8. package org.hd.util;  
  9.   
  10. import java.io.File;  
  11. import java.io.FileNotFoundException;  
  12. import java.io.FileOutputStream;  
  13. import java.io.IOException;  
  14. import java.text.SimpleDateFormat;  
  15. import java.util.Date;  
  16.   
  17. import net.sf.json.JSONObject;  
  18.   
  19. import org.hd.util.BlobUtil;  
  20.   
  21. import com.itextpdf.text.BaseColor;  
  22. import com.itextpdf.text.Document;  
  23. import com.itextpdf.text.DocumentException;  
  24. import com.itextpdf.text.Element;  
  25. import com.itextpdf.text.Font;  
  26. import com.itextpdf.text.Paragraph;  
  27. import com.itextpdf.text.Phrase;  
  28. import com.itextpdf.text.Rectangle;  
  29. import com.itextpdf.text.pdf.BaseFont;  
  30. import com.itextpdf.text.pdf.PdfPCell;  
  31. import com.itextpdf.text.pdf.PdfPRow;  
  32. import com.itextpdf.text.pdf.PdfPTable;  
  33. import com.itextpdf.text.pdf.PdfWriter;  
  34.   
  35. public class ExportPdfUtil {  
  36.   
  37.     /** The resulting PDF file. */  
  38.     public static final String RESULT = "D:/column_widths.pdf";  
  39.     public static String WEBCONTENT_PATH="";  
  40.     public static String BASE_PATH="";  
  41.     public static String TEMP_PDF_PATH="";//临时pdf目录  
  42.       
  43.     public static String DirTypePdf="pdf";  
  44.     static{  
  45.   
  46.         String clapath=BlobUtil.class.getResource("/").getPath();  
  47.         File claFile=new File(clapath);  
  48.         String basePath=claFile.getParentFile().getParentFile().getPath();  
  49.         ExportPdfUtil.WEBCONTENT_PATH=basePath;  
  50.         ExportPdfUtil.BASE_PATH=basePath+"\\tempExport";  
  51.         ExportPdfUtil.TEMP_PDF_PATH=ExportPdfUtil.BASE_PATH+"\\pdf";  
  52.         File tempBase=new File(ExportPdfUtil.BASE_PATH);  
  53.         if(!tempBase.exists()){  
  54.             tempBase.mkdir();  
  55.         }  
  56.         File tempPdf=new File(ExportPdfUtil.TEMP_PDF_PATH);  
  57.         if(!tempPdf.exists()){  
  58.             tempPdf.mkdir();  
  59.         }  
  60.           
  61.         /*  
  62.   
  63.          */  
  64.         System.out.println("--ExportPdfUtil.WEBCONTENT_PATH--"+ExportPdfUtil.WEBCONTENT_PATH);  
  65.         System.out.println("--ExportPdfUtil.BASE_PATH--"+ExportPdfUtil.BASE_PATH);  
  66.         System.out.println("--ExportPdfUtil.TEMP_PDF_PATH--"+ExportPdfUtil.TEMP_PDF_PATH);  
  67.       
  68.     }  
  69.     //直接使用json创建pdf文件  
  70.     public static String createPdfWithJson(String resjson){  
  71.         String info="";  
  72.         JSONObject jo=JSONObject.fromObject(resjson);  
  73.           
  74.         String title=(String)jo.get("title");  
  75.         String resTableheaders=(String)jo.get("resTableheaders");  
  76.         String resList=(String)jo.get("resList");  
  77.           
  78.         String[] resTableheadersArr=ExportExcelUtil.getResTableheadersFromAllStr(resTableheaders);  
  79.         String[][] resListArr=ExportExcelUtil.getResListFromAllStr(resList);  
  80.           
  81.         info=ExportPdfUtil.createPdf(title, resTableheadersArr, resListArr);  
  82.           
  83.         return info;  
  84.     }  
  85.     /**  
  86.      * 写文件,创建pdf  
  87.      * @param filepath  
  88.      * @param document  
  89.      * @return  
  90.      */  
  91.     public static String createPdf(String title,String[] titles,String[][] dataSet){  
  92.         String respath=ExportPdfUtil.TEMP_PDF_PATH;  
  93.         String filename=ExportPdfUtil.getRandomDateStr();  
  94.         Document document = new Document();  
  95.         Rectangle rectangle=new Rectangle(1024,900);  
  96.         document.setPageSize(rectangle);  
  97.           
  98.         if(document==null||filename==null||filename.trim().equals("")){  
  99.             return "error";  
  100.         }  
  101.         try {  
  102.             String abpath1=respath+"\\"+filename.trim()+".pdf";  
  103.             respath="tempExport/pdf/"+filename.trim()+".pdf";;  
  104.             PdfWriter.getInstance(document, new FileOutputStream(abpath1));  
  105.             document.open();  
  106.             //标题设置  
  107.             String titlestr=title==null?"":title;  
  108. //          Phrase phtitle=new Phrase(titlestr,ExportPdfUtil.getChineseFont());  
  109.             Paragraph phtitle2=new Paragraph(titlestr,ExportPdfUtil.getChineseFont());  
  110.             phtitle2.setAlignment(Element.ALIGN_CENTER);  
  111.               
  112.             document.add(phtitle2);  
  113.               
  114.             PdfPTable table = ExportPdfUtil.createTable(title,titles, dataSet);  
  115.             table.setSpacingBefore(15);  
  116.             table.setSpacingAfter(15);  
  117.             document.add(table);  
  118.               
  119.             document.close();  
  120.         } catch (FileNotFoundException e) {  
  121.             e.printStackTrace();  
  122.         } catch (DocumentException e) {  
  123.             e.printStackTrace();  
  124.         }  
  125.         System.out.println("web路径:"+respath);  
  126.         return respath;  
  127.     }  
  128.       
  129.     public static PdfPTable createTable(String title,String[] titles,String[][] dataSet) throws DocumentException {  
  130.         if(titles==null||titles.length==0){  
  131.             return null;  
  132.         }  
  133.         PdfPTable table = new PdfPTable(titles.length);  
  134.           
  135.         //表的样式设置--对齐   
  136.         table.setWidthPercentage(90);  
  137.         table.setHorizontalAlignment(Element.ALIGN_CENTER);  
  138.           
  139.         //表头设置  
  140.         float[] headerLength=new float[titles.length];  
  141.         for(int i=0;i<headerLength.length;i++){  
  142.             String ti=titles[i]==null?"":titles[i];  
  143.             int len=ti.length();  
  144.             headerLength[i]=15*len+20;  
  145.         }  
  146.         table.setTotalWidth(headerLength);  
  147.         table.setLockedWidth(true);  
  148.           
  149.         PdfPCell cell;  
  150.         //表头  
  151.         for(int k=0;k<titles.length;k++){  
  152.             String str=titles[k]==null?"":titles[k];  
  153.             cell = new PdfPCell(new Phrase(str,ExportPdfUtil.getChineseFont()));  
  154.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);  
  155.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  
  156.             cell.setNoWrap(true);  
  157.             cell.setColspan(1);  
  158.               
  159.             BaseColor bc=new BaseColor(95,158,160);  
  160.             cell.setBackgroundColor(bc);  
  161.               
  162.             table.addCell(cell);  
  163.         }  
  164.         //表数据  
  165.         for(int i=0;i<dataSet.length;i++){  
  166.             String[] row=dataSet[i];  
  167.             if(row==null||row.length==0){  
  168.                 continue;  
  169.             }  
  170.             for(int k=0;k<row.length;k++){  
  171.                 String str=row[k]==null?"":row[k];  
  172.                 cell = new PdfPCell(new Phrase(str,ExportPdfUtil.getChineseFontForTableCellOne()));  
  173.                 cell.setHorizontalAlignment(Element.ALIGN_CENTER);  
  174.                 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  
  175.                 cell.setNoWrap(true);  
  176.                 cell.setColspan(1);  
  177.                 table.addCell(cell);  
  178.             }  
  179.         }  
  180.         return table;  
  181.     }  
  182.       
  183.     public static Font getChineseFont(){  
  184.         BaseFont bf;  
  185.         Font fontChinese=null;  
  186.         try {  
  187.             bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  188.             fontChinese=new Font(bf,12,Font.NORMAL);  
  189.         } catch (DocumentException e) {  
  190.             e.printStackTrace();  
  191.         } catch (IOException e) {  
  192.             e.printStackTrace();  
  193.         }  
  194.           
  195.         return fontChinese;  
  196.     }  
  197.     public static Font getChineseFontForTableCellOne(){  
  198.         BaseFont bf;  
  199.         Font fontChinese=null;  
  200.         try {  
  201.             bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  202.             fontChinese=new Font(bf,10,Font.NORMAL);  
  203.         } catch (DocumentException e) {  
  204.             e.printStackTrace();  
  205.         } catch (IOException e) {  
  206.             e.printStackTrace();  
  207.         }  
  208.           
  209.         return fontChinese;  
  210.     }  
  211.     //随机日期字符串  
  212.     public static String getRandomDateStr(){  
  213.         String res="";  
  214.         SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");  
  215.         res=sdf.format(new Date());  
  216.         String a=String.valueOf((new Date()).getTime());  
  217.         return res+"pdf".trim()+a;  
  218.     }  
  219.   
  220.     /**  
  221.      * Main method.  
  222.      * @param args no arguments needed  
  223.      * @throws DocumentException   
  224.      * @throws IOException  
  225.      */  
  226.     public static void main(String[] args) throws IOException, DocumentException {  
  227.         String title="呼入汇总11";  
  228.         String[] titles=new String[]{"t1表头","t2表头","t3表头","t4表头","t5表头"};  
  229.         String[][] dataSet=new String[2][5];  
  230.         dataSet[0]=new String[]{"d11数据","d12数据","d13数据","d14数据","d15数据"};  
  231.         dataSet[1]=new String[]{"d21数据","d22数据","d23数据","d24数据","d25数据"};  
  232.         ExportPdfUtil.createPdf(title,titles,dataSet);  
  233.     }  
  234. }  


excel:

[html]  view plain copy
  1. package org.hd.util;  
  2.   
  3. import net.sf.json.JSONObject;  
  4. import org.apache.poi.xssf.usermodel.*;  
  5. import org.apache.poi.ss.util.CellRangeAddress;  
  6. import org.apache.poi.ss.usermodel.*;  
  7. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  8.   
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11. import java.util.Map;  
  12. import java.util.HashMap;  
  13. import java.io.File;  
  14. import java.io.FileNotFoundException;  
  15. import java.io.FileOutputStream;  
  16. import java.io.OutputStream;  
  17.   
  18. import javax.servlet.http.HttpServletResponse;  
  19.   
  20. public class ExportExcelUtil {  
  21.       
  22.     public static String WEBCONTENT_PATH="";  
  23.     public static String BASE_PATH="";  
  24.     public static String TEMP_EXCEL_PATH="";//临时excel目录  
  25.     public static String TEMP_WORD_PATH="";//临时word目录  
  26.       
  27.     public static String DirTypeExcel="excel";  
  28.     public static String DirTypeWord="word";  
  29.     static{  
  30.   
  31.         String clapath=BlobUtil.class.getResource("/").getPath();  
  32.         File claFile=new File(clapath);  
  33.         String basePath=claFile.getParentFile().getParentFile().getPath();  
  34.         ExportExcelUtil.WEBCONTENT_PATH=basePath;  
  35.         ExportExcelUtil.BASE_PATH=basePath+"\\tempExport";  
  36.         ExportExcelUtil.TEMP_EXCEL_PATH=ExportExcelUtil.BASE_PATH+"\\excel";  
  37.         ExportExcelUtil.TEMP_WORD_PATH=ExportExcelUtil.BASE_PATH+"\\word";  
  38.         File tempBase=new File(ExportExcelUtil.BASE_PATH);  
  39.         if(!tempBase.exists()){  
  40.             tempBase.mkdir();  
  41.         }  
  42.         File tempExcel=new File(ExportExcelUtil.TEMP_EXCEL_PATH);  
  43.         if(!tempExcel.exists()){  
  44.             tempExcel.mkdir();  
  45.         }  
  46.         File tempWord=new File(ExportExcelUtil.TEMP_WORD_PATH);  
  47.         if(!tempWord.exists()){  
  48.             tempWord.mkdir();  
  49.         }  
  50.           
  51.         /*  
  52. --ExportExcelUtil.WEBCONTENT_PATH--D:\MyProject\my-workSpace\ROOT\WebContent  
  53. --ExportExcelUtil.BASE_PATH--D:\MyProject\my-workSpace\ROOT\WebContent\tempExport  
  54. --ExportExcelUtil.TEMP_EXCEL_PATH--D:\MyProject\my-workSpace\ROOT\WebContent\tempExport\excel  
  55. --ExportExcelUtil.TEMP_WORD_PATH--D:\MyProject\my-workSpace\ROOT\WebContent\tempExport\word  
  56. --ExportExcelUtil.TEMP_PDF_PATH--D:\MyProject\my-workSpace\ROOT\WebContent\tempExport\pdf  
  57.   
  58.          */  
  59.         System.out.println("--ExportExcelUtil.WEBCONTENT_PATH--"+ExportExcelUtil.WEBCONTENT_PATH);  
  60.         System.out.println("--ExportExcelUtil.BASE_PATH--"+ExportExcelUtil.BASE_PATH);  
  61.         System.out.println("--ExportExcelUtil.TEMP_EXCEL_PATH--"+ExportExcelUtil.TEMP_EXCEL_PATH);  
  62.         System.out.println("--ExportExcelUtil.TEMP_WORD_PATH--"+ExportExcelUtil.TEMP_WORD_PATH);  
  63.       
  64.     }  
  65.   
  66.     /*  
  67.      resjson--{"title":"呼入汇总","resTableheaders":"日期,坐席总数,呼入总数,总失败次数,咨询次数,转移次数 ,总通话时长,平均通话时长,平均振铃次数,平均振铃时长","resList":"2012-10-17,5,36,3,3,0,54.20,1.64,0,0.11|2012-10-18,5,32,5,1,0,47.10,1.81,0,0.12|2012-10-19,5,32,3,2,0,37.45,1.29,0,0.12|2012-10-22,5,54,6,5,0,92.87,1.98,0,0.09|"}  
  68. title--呼入汇总  
  69. resTableheaders--日期,坐席总数,呼入总数,总失败次数,咨询次数,转移次数 ,总通话时长,平均通话时长,平均振铃次数,平均振铃时长  
  70. resList--2012-10-17,5,36,3,3,0,54.20,1.64,0,0.11|2012-10-18,5,32,5,1,0,47.10,1.81,0,0.12|2012-10-19,5,32,3,2,0,37.45,1.29,0,0.12|2012-10-22,5,54,6,5,0,92.87,1.98,0,0.09|  
  71.        
  72.      *  
  73.     resjson--{"title":"呼入汇总","resTableheaders":"日期,坐席总数,呼入总数,总失败次数,咨询次数,转移次数 ,总通话时长,平均通话时长,平均振铃次数,平均振铃时长","resList":""}  
  74. title--呼入汇总  
  75. resTableheaders--日期,坐席总数,呼入总数,总失败次数,咨询次数,转移次数 ,总通话时长,平均通话时长,平均振铃次数,平均振铃时长  
  76. resList--  
  77.      */  
  78.     public static String exportExcelFromAllStr(String resjson,String clientFileName,OutputStream os,HttpServletResponse response){  
  79.         String info="";  
  80.         JSONObject jo=JSONObject.fromObject(resjson);  
  81.           
  82.         String title=(String)jo.get("title");  
  83.         String resTableheaders=(String)jo.get("resTableheaders");  
  84.         String resList=(String)jo.get("resList");  
  85.           
  86.         System.out.println("title--"+title);  
  87.         System.out.println("resTableheaders--"+resTableheaders);  
  88.         ExportExcelUtil.printResListFromAllStr(ExportExcelUtil.getResListFromAllStr(resList));  
  89.           
  90.         //导出  
  91.         Workbook wb=ExportExcelUtil.createWorkbook(null,title, ExportExcelUtil.getResTableheadersFromAllStr(resTableheaders), ExportExcelUtil.getResListFromAllStr(resList));  
  92.         String res=ExportExcelUtil.exportExcelFileOnWeb(wb, clientFileName, os, response);  
  93.         if(res==null||res.trim().equals("error")){  
  94.             info="error";  
  95.         }else{  
  96.             info=res.trim();  
  97.         }  
  98.         return info;  
  99.     }  
  100.       
  101.     public static String exportExcelFromAllStrOnServerDownLoad(String resjson,String clientFileName){  
  102.         String infopath="";  
  103.         JSONObject jo=JSONObject.fromObject(resjson);  
  104.           
  105.         String title=(String)jo.get("title");  
  106.         String resTableheaders=(String)jo.get("resTableheaders");  
  107.         String resList=(String)jo.get("resList");  
  108.           
  109.         System.out.println("title--"+title);  
  110.         System.out.println("resTableheaders--"+resTableheaders);  
  111.         ExportExcelUtil.printResListFromAllStr(ExportExcelUtil.getResListFromAllStr(resList));  
  112.           
  113.         //导出  
  114.         Workbook wb=ExportExcelUtil.createWorkbook(null,title, ExportExcelUtil.getResTableheadersFromAllStr(resTableheaders), ExportExcelUtil.getResListFromAllStr(resList));  
  115.         String res=ExportExcelUtil.exportExcelFile(wb, clientFileName, null);  
  116.         if(res==null||res.trim().equals("error")){  
  117.             infopath="error";  
  118.         }else{  
  119.             infopath=res.trim();  
  120.         }  
  121.         return infopath;  
  122.     }  
  123.       
  124.     //resTableheaders--日期,坐席总数,呼入总数,总失败次数,咨询次数,转移次数 ,总通话时长,平均通话时长,平均振铃次数,平均振铃时长  
  125.     public static String[] getResTableheadersFromAllStr(String resTableheaders){  
  126.         String[] arrResTableheaders=resTableheaders.split(",");  
  127.         return arrResTableheaders;  
  128.     }  
  129.     //resList--2012-10-17,5,36,3,3,0,54.20,1.64,0,0.11|2012-10-18,5,32,5,1,0,47.10,1.81,0,0.12|2012-10-19,5,32,3,2,0,37.45,1.29,0,0.12|2012-10-22,5,54,6,5,0,92.87,1.98,0,0.09|  
  130.     public static String[][] getResListFromAllStr(String resList){  
  131.         String[][] res=null;  
  132.           
  133.         String[] arrObjList=null;  
  134.         String[] arrObj=null;  
  135.         if(resList==null||resList.trim().equals("")){  
  136.         }else{  
  137.             arrObjList=resList.split("suolong");  
  138.               
  139.             if(arrObjList!=null&&arrObjList.length>=1){  
  140.                 String vo=(String)arrObjList[0];  
  141.                 arrObj=vo.split(",");  
  142.                 if(arrObj!=null&&arrObj.length>=1){  
  143.                     res=new String[arrObjList.length][arrObj.length];  
  144.                     //放数据  
  145.                     for(int i=0;i<arrObjList.length;i++){  
  146.                         String vo2=(String)arrObjList[i];  
  147.                         String[] arrObj2=vo2.split(",");  
  148.                         for(int k=0;k<arrObj2.length;k++){  
  149.                             res[i][k]=arrObj2[k];  
  150.                         }  
  151.                     }  
  152.                 }  
  153.             }else{  
  154.                   
  155.             }  
  156.         }  
  157.           
  158.         return res;  
  159.     }  
  160.     //打印表格数据  
  161.     public static void printResListFromAllStr(String[][] res){  
  162.         if(res==null){  
  163.             System.out.println("res[][] is null");  
  164.         }else{  
  165.             System.out.println("res[][] 行数:"+res.length);  
  166.             if(res.length>=1){  
  167.                 System.out.println("res[][] 列数:"+res[0].length);  
  168.                 for(int i=0;i<res.length;i++){  
  169.                     String line="";  
  170.                     for(int k=0;k<res[i].length;k++){  
  171.                         line+="res["+i+"]["+k+"]"+res[i][k]+",";  
  172.                     }  
  173.                     line+="\r\n";  
  174.                     System.out.println(line);  
  175.                 }  
  176.             }  
  177.         }  
  178.           
  179.     }  
  180.       
  181.     public static void main(String[] ss){  
  182.         String[] titles1={"日期","平均振铃时长平均振铃时长","总失败次数"};  
  183.         String[][] sample_data1={  
  184.                 {"2012-09-08 18:12:33  kk","12","13"},  
  185.                 {"21","22","23"}  
  186.         };  
  187.         Workbook wb=ExportExcelUtil.createWorkbook(null,"gg2", titles1, sample_data1);  
  188.         String res=ExportExcelUtil.exportExcelFile(wb, "测试22",null);  
  189.         System.out.print("res");  
  190.     }  
  191.     /**  
  192.      * 导出到客户端本地  
  193.      * @param wb  
  194.      * @param fileName  
  195.      * @param os  
  196.      * @return  
  197.      */  
  198.     public static String exportExcelFileOnWeb(Workbook wb,String fileName,OutputStream os,HttpServletResponse response){  
  199.         String info="";  
  200.         if(wb==null){  
  201.             info="error";  
  202.         }else{  
  203.             String fileName2 = "";  
  204.             if(fileName==null||fileName.trim().equals("")){  
  205.                 fileName2=ExportExcelUtil.getRandomDateStr()+".xls";  
  206.             }else{  
  207.                 fileName2=fileName.trim()+".xls";  
  208.             }  
  209.             if(wb instanceof XSSFWorkbook) {  
  210.                 fileName2 += "x";  
  211.             }  
  212.               
  213.             try {  
  214.                 info="tempExport/excel/"+fileName2;  
  215. //              response.setContentType( "application/vnd.ms-excel");//2003  
  216. //              response.setContentType("application/ms-excel"); //2003  
  217.                 response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//2007  
  218.                   
  219. //              response.setContentType("octets/stream");//压缩文件  
  220. //              response.setContentType("application/x-msdownload");//压缩文件  
  221.                 response.addHeader("Content-Disposition","attachment;filename="+info.trim());  
  222.                   
  223.                 wb.write(os);  
  224.                 os.flush();  
  225.                 os.close();  
  226.                   
  227.                 System.out.println("成功导出到客户端");  
  228.             } catch (Exception e) {  
  229.                 e.printStackTrace();  
  230.             }  
  231.         }  
  232.           
  233.         return info;  
  234.     }  
  235.     /**  
  236.      * 根据Workbook和文件名导出文件  
  237.      * @param wb  
  238.      * @param fileName  
  239.      * tempExport/excel/xxx.xlsx  
  240.      */  
  241.     public static String exportExcelFile(Workbook wb,String fileName,String webPath){  
  242.         String info="";  
  243.         if(wb==null){  
  244.             info="error";  
  245.         }else{  
  246.             String fileName2 = "";  
  247.             if(fileName==null||fileName.trim().equals("")){  
  248.                 fileName2=ExportExcelUtil.getRandomDateStr()+".xls";  
  249.             }else{  
  250.                 fileName2=fileName.trim()+".xls";  
  251.             }  
  252.             if(wb instanceof XSSFWorkbook) fileName2 += "x";  
  253.               
  254.             String wholeFilePath="";  
  255.             if(webPath==null||webPath.trim().equals("")){  
  256.                 wholeFilePath=ExportExcelUtil.TEMP_EXCEL_PATH+"\\"+fileName2;  
  257.             }else{  
  258.                 wholeFilePath=webPath.trim()+"\\"+fileName2;  
  259.             }  
  260.             wholeFilePath=wholeFilePath.replace("\\", "/");  
  261.             FileOutputStream out;  
  262.             try {  
  263.                 out = new FileOutputStream(wholeFilePath);  
  264.                 wb.write(out);  
  265.                 out.close();  
  266.                 info="tempExport/excel/"+fileName2;  
  267.                 System.out.println("成功导出到服务器的临时目录下:"+wholeFilePath);  
  268.                 System.out.println("返回server路径"+info);  
  269.             } catch (Exception e) {  
  270.                 e.printStackTrace();  
  271.             }  
  272.         }  
  273.           
  274.         return info;  
  275.     }  
  276.     //随机日期字符串  
  277.     public static String getRandomDateStr(){  
  278.         String res="";  
  279.         SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");  
  280.         res=sdf.format(new Date());  
  281.         String a=String.valueOf((new Date()).getTime());  
  282.         return res+"excel".trim()+a;  
  283.     }  
  284.     //业务逻辑,产生一个工作簿  
  285.     public static Workbook createWorkbook(String typeparam,String tableHeader,String[] titles,String[][] sample_data){  
  286.         Workbook wb=null;  
  287.         try{  
  288.             if(typeparam==null){  
  289.                 wb = new XSSFWorkbook();  
  290.             }  
  291.             else if(typeparam.length() > 0 && typeparam.equals("2003")) {wb = new HSSFWorkbook();}  
  292.             else {wb = new XSSFWorkbook();}  
  293.   
  294.             Map<String, CellStyle> styles = createStyles(wb);  
  295.               
  296.             String tableHeader2="";  
  297.             if(tableHeader==null||tableHeader.trim().equals("")){  
  298.                 tableHeader2=ExportExcelUtil.getRandomDateStr();  
  299.             }else{  
  300.                 tableHeader2=tableHeader.trim();  
  301.             }  
  302.             Sheet sheet = wb.createSheet(tableHeader2);  
  303.               
  304.             PrintSetup printSetup = sheet.getPrintSetup();  
  305.             printSetup.setLandscape(true);  
  306.             sheet.setFitToPage(true);  
  307.             sheet.setHorizontallyCenter(true);  
  308.   
  309.             //title row  
  310.             Row titleRow = sheet.createRow(0);  
  311.             titleRow.setHeightInPoints(35);  
  312.             Cell titleCell = titleRow.createCell(0);  
  313.             titleCell.setCellValue(tableHeader2);  
  314.             titleCell.setCellStyle(styles.get("title"));  
  315.             sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));  
  316.   
  317.             //header row  
  318.             Row headerRow = sheet.createRow(1);  
  319.             headerRow.setHeightInPoints(30);  
  320.             Cell headerCell;  
  321.             if(titles!=null){  
  322.                 for (int i = 0; i < titles.length; i++) {  
  323.                     headerCell = headerRow.createCell(i);  
  324.                     headerCell.setCellValue(titles[i]);  
  325.                     headerCell.setCellStyle(styles.get("header"));  
  326.                 }  
  327.             }  
  328.               
  329.             // data row  
  330.             if(sample_data!=null){  
  331.                 for (int i = 0; i < sample_data.length; i++) {  
  332.                     Row row = sheet.createRow(2+i);  
  333.                     row.setHeightInPoints(20);  
  334.                     for (int j = 0; j < sample_data[i].length; j++) {  
  335.                         Cell dataCell=row.createCell(j);  
  336.                         dataCell.setCellStyle(styles.get("cell"));  
  337.                           
  338.                         if(sample_data[i][j] == null) continue;  
  339.                         if(sample_data[i][j] instanceof String) {  
  340.                             dataCell.setCellValue((String)sample_data[i][j]);  
  341.                         } else {  
  342.                             dataCell.setCellValue(sample_data[i][j].toString());  
  343.                         }  
  344.                     }  
  345.                 }  
  346.             }  
  347.               
  348.             //finally set column widths, the width is measured in units of 1/256th of a character width  
  349.             if(titles!=null){  
  350.                 for (int i = 0; i < titles.length; i++) {  
  351.                     int tlen1=(titles[i]==null)?7:titles[i].length();  
  352.                     int tlen=(tlen1<7)?7:tlen1;  
  353.                       
  354.                     int len=(tlen*256*3)+5;  
  355.                     sheet.setColumnWidth(i, len);  //6 characters wide  
  356.                 }  
  357.             }  
  358.               
  359.         }catch(Exception ee){  
  360.             ee.printStackTrace();  
  361.         }  
  362.           
  363.         return wb;  
  364.     }  
  365.   
  366.     /**公用的css样式集,放在一个map中。  
  367.      * Create a library of cell styles  
  368.      */  
  369.     private static Map<String, CellStyle> createStyles(Workbook wb){  
  370.         Map<String, CellStyle> stylesMap = new HashMap<String, CellStyle>();  
  371.           
  372.         CellStyle style;  
  373.           
  374.         Font titleFont = wb.createFont();  
  375.         titleFont.setFontHeightInPoints((short)18);  
  376.         titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  377.         style = wb.createCellStyle();  
  378.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  379.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  380.         style.setFont(titleFont);  
  381.         stylesMap.put("title", style);  
  382.   
  383.         Font monthFont = wb.createFont();  
  384.         monthFont.setFontHeightInPoints((short)11);  
  385.         monthFont.setColor(IndexedColors.BLACK.getIndex());  
  386.         style = wb.createCellStyle();  
  387.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  388.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  389.         style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());  
  390.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  391.         style.setFont(monthFont);  
  392.         style.setWrapText(true);  
  393.         style.setBorderRight(CellStyle.BORDER_THIN);  
  394.         style.setBorderTop(CellStyle.BORDER_THIN);  
  395.         stylesMap.put("header", style);  
  396.   
  397.         style = wb.createCellStyle();  
  398.         Font cellwb.createFont();  
  399.         cell.setColor(IndexedColors.BLUE.getIndex());  
  400.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  401.         style.setWrapText(true);  
  402.         style.setBorderRight(CellStyle.BORDER_THIN);  
  403.         style.setRightBorderColor(IndexedColors.BLACK.getIndex());  
  404.         style.setBorderLeft(CellStyle.BORDER_THIN);  
  405.         style.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
  406.         style.setBorderTop(CellStyle.BORDER_THIN);  
  407.         style.setTopBorderColor(IndexedColors.BLACK.getIndex());  
  408.         style.setBorderBottom(CellStyle.BORDER_THIN);  
  409.         style.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
  410.         style.setFillForegroundColor(IndexedColors.BLUE.getIndex());  
  411.         stylesMap.put("cell", style);  
  412.   
  413.         style = wb.createCellStyle();  
  414.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  415.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  416.         style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());  
  417.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  418.         style.setDataFormat(wb.createDataFormat().getFormat("0.00"));  
  419.         stylesMap.put("formula", style);  
  420.   
  421.         style = wb.createCellStyle();  
  422.         style.setAlignment(CellStyle.ALIGN_CENTER);  
  423.         style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
  424.         style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());  
  425.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  426.         style.setDataFormat(wb.createDataFormat().getFormat("0.00"));  
  427.         stylesMap.put("formula_2", style);  
  428.   
  429.         return stylesMap;  
  430.     }  
  431.   
  432.   
  433. }  


 页面访问,之前设置过setContentType,没有弹出文件保存框的原因也找到了。

就是下载的请求不能用ajax,(或许需要其他设置,这里我做的时候就是不行),

请求使用window.location.href就可以弹出保存框,使用ajax就没反应,在回调函数中

返回的是乱码。原因不详,总之别用ajax调用下载文件的servlert请求。

 

[html]  view plain copy
  1. function pdfservlet(){  
  2.     var resjson=getResJson();  
  3.     var urlpath1=path+'/ExportPdfServlet?dd='+Math.random()+'&resjson='+resjson;  
  4.     var urlpath2=encodeURI(urlpath1);  
  5.     var urlpath=encodeURI(urlpath2);  
  6.     window.location.href=urlpath;  
  7. }  
  8. function excelServlet(){  
  9.     var resjson=getResJson();  
  10.     //var urlpath1=path+'/PdfItextServlet?dd='+Math.random()+'&resjson='+resjson;  
  11.     var urlpath1=path+'/ExportExcelServlet?dd='+Math.random()+'&resjson='+resjson;  
  12.     var urlpath2=encodeURI(urlpath1);  
  13.     var urlpath=encodeURI(urlpath2);  
  14.     window.location.href=urlpath;  
  15.       
  16. }  


 

 

 思路(二)是发请求在服务器生成文件,ajax访问返回这个文件的url,在回调函数中请求这个url。

思路不好,还是可行的。代码如下:

pdf

[html]  view plain copy
  1. package org.hd.report.action.pdf;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import net.sf.json.JSONObject;  
  11.   
  12. import org.apache.struts2.ServletActionContext;  
  13. import org.hd.report.model.GreenPageVo;  
  14. import org.hd.report.service.ReportService;  
  15. import org.hd.report.service.RptService;  
  16. import org.hd.util.ExportExcelUtil;  
  17. import org.hd.util.ExportPdfUtil;  
  18. import org.rd.framework.common.container.ContainerManager;  
  19. import org.rd.framework.query.support.PaginationSupport;  
  20. import org.rd.framework.struts.action.CommonAction;  
  21.   
  22. import com.opensymphony.xwork2.ActionContext;  
  23.   
  24. //呼入汇总  
  25. public class ExportTableDataToPdfAction  extends CommonAction{  
  26.     private RptService rptService = (RptService)ContainerManager.getComponent(RptService.BEAN_ID);  
  27.       
  28.     public String exportPdfInSummary() throws Exception{  
  29.           
  30.         ActionContext ctx = ActionContext.getContext();  
  31.         HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);   
  32.         HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);   
  33.         response.setCharacterEncoding("UTF-8");  
  34. //      response.setContentType("application/pdf");  
  35. //      response.setContentType("text/xml");  
  36.         PrintWriter out = response.getWriter();  
  37.           
  38.         String resjsonrequest.getParameter("resjson") != null ? request.getParameter("resjson").trim() : "";  
  39.         resjson=java.net.URLDecoder.decode(resjson,"UTF-8");  
  40.         System.out.println("resjson from page--"+resjson);  
  41.           
  42.         String clientFileName="";  
  43.         String infopath=ExportPdfUtil.createPdfWithJson(resjson);  
  44.           
  45.         out.println(infopath);  
  46.           
  47.         return NONE;  
  48.     }  
  49.     public String execute() throws Exception{  
  50.         return SUCCESS;  
  51.     }  
  52.   
  53. }  


excel

[html]  view plain copy
  1. package org.hd.report.action.excel;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import net.sf.json.JSONObject;  
  11.   
  12. import org.apache.struts2.ServletActionContext;  
  13. import org.hd.report.model.GreenPageVo;  
  14. import org.hd.report.service.ReportService;  
  15. import org.hd.report.service.RptService;  
  16. import org.hd.util.ExportExcelUtil;  
  17. import org.rd.framework.common.container.ContainerManager;  
  18. import org.rd.framework.query.support.PaginationSupport;  
  19. import org.rd.framework.struts.action.CommonAction;  
  20.   
  21. import com.opensymphony.xwork2.ActionContext;  
  22.   
  23. //呼入汇总  
  24. public class ExportTableDataToExcelAction  extends CommonAction{  
  25.     private RptService rptService = (RptService)ContainerManager.getComponent(RptService.BEAN_ID);  
  26.       
  27.     public String exportExcelInSummary() throws Exception{  
  28.           
  29.         ActionContext ctx = ActionContext.getContext();  
  30.         HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);   
  31.         HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);   
  32.         response.setCharacterEncoding("UTF-8");  
  33.           
  34. //      response.setContentType( "application/vnd.ms-excel");  
  35. //      response.addHeader("Content-Disposition","attachment;filename=output.xlsx");  
  36.           
  37. //      response.setContentType("application/ms-excel");   
  38. //      response.addHeader("Content-Disposition","attachment;filename=output.xlsx");  
  39.           
  40. //      response.setContentType("octets/stream");  
  41. //        response.addHeader("Content-Disposition","attachment;filename=output.xlsx");  
  42.   
  43.           
  44.         PrintWriter out = response.getWriter();  
  45. //      OutputStream os=response.getOutputStream();  
  46.           
  47.         String resjsonrequest.getParameter("resjson") != null ? request.getParameter("resjson").trim() : "";  
  48.         resjson=java.net.URLDecoder.decode(resjson,"UTF-8");  
  49.         System.out.println("resjson from page--"+resjson);  
  50.           
  51.         String clientFileName="";  
  52. //      String info=ExportExcelUtil.exportExcelFromAllStr(resjson, clientFileName, os);  
  53.         String infopath=ExportExcelUtil.exportExcelFromAllStrOnServerDownLoad(resjson, clientFileName);  
  54.           
  55.         out.println(infopath);  
  56.           
  57.         return NONE;  
  58.     }  
  59.     public String execute() throws Exception{  
  60.         return SUCCESS;  
  61.     }  
  62.   
  63. }  


struts.xml

[html]  view plain copy
  1. <!-- 导出 -->  
  2.     <action name="exportExcelInSummary" class="org.hd.report.action.excel.ExportTableDataToExcelAction" method="exportExcelInSummary">  
  3.     </action>  
  4.     <action name="exportPdfInSummary" class="org.hd.report.action.pdf.ExportTableDataToPdfAction" method="exportPdfInSummary">  
  5.     </action>  


页面调用:

[html]  view plain copy
  1. function excelAction(){  
  2.     var resjson=getResJson();  
  3.     //var urlpath1=path+'/PdfItextServlet?dd='+Math.random()+'&resjson='+resjson;  
  4.     var urlpath1=path+'/report/exportExcelInSummary.action?dd='+Math.random()+'&resjson='+resjson;  
  5.     var urlpath2=encodeURI(urlpath1);  
  6.     var urlpath=encodeURI(urlpath2);  
  7.     //alert(urlpath);  
  8.     $.ajax({  
  9.            type: "POST",  
  10.            url: urlpath,  
  11.            success: excelActionBack  
  12.         });  
  13.       
  14. }  
  15. function excelActionBack(data){  
  16.     alert(data+"------");  
  17.     var data1=$.trim(data);  
  18.     var downpath=path+"/"+data1;  
  19.     window.location.href=downpath;  
  20. }  
  21. function pdfAction(){  
  22.     var resjson=getResJson();  
  23.     //var urlpath1=path+'/PdfItextServlet?dd='+Math.random()+'&resjson='+resjson;  
  24.     var urlpath1=path+'/report/exportPdfInSummary.action?dd='+Math.random()+'&resjson='+resjson;  
  25.     var urlpath2=encodeURI(urlpath1);  
  26.     var urlpath=encodeURI(urlpath2);  
  27.     //alert(urlpath);  
  28.     $.ajax({  
  29.            type: "POST",  
  30.            url: urlpath,  
  31.            success:pdfActionBack  
  32.         });  
  33. }  
  34.   
  35. function pdfActionBack(data){  
  36.     alert(data+"------");  
  37.     var data1=$.trim(data);  
  38.     var downpath=path+"/"+data1;  
  39.     window.location.href=downpath;  
  40. }  


getResJson()是拼装json数据的方法,业务逻辑。

至于请求的url都调用了2遍encodeURI(),就是为了防止中文参数乱码。

记住必须是2次。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值