java操作office和pdf文件页面列表导出cvs,excel、pdf报表.

来源:互联网 发布:韩顺平java和java ee 编辑:程序博客网 时间:2024/05/16 15:41
 

        在平常的开发中我们常常遇到不仅仅只是导出excel报表的情况。有时候也需要导出pdf或者CSV报表。其实原理都差不多。刚开始本来不打算也这篇博客介绍这个的。感觉这篇博客和前面的博客有点雷同。原理基本都一样。但想了想。有时候可能有些童鞋遇到这样的需求会无从下手。所以还是记录下来。帮助一下那些需要这个需求的童鞋。如果你对前面几篇博客的原理都搞明白了。这篇博客你完全可以不看了。仅仅只是代码的实现不同而已。好了。下面我们来看一下需求吧。

这个图就是我们的需求

                            

     就像你看到的一样。我们的需求就是列表内容是从数据库中读出来的。而我们想把从数据库得到的这个列表导出pdfcsvexcel报表。也不多说了。看代码吧:

复制代码
  1 package com.bzu.csh;  2   3 import java.io.ByteArrayOutputStream;  4 import java.io.File;  5 import java.io.FileOutputStream;  6 import java.io.OutputStream;  7 import java.util.ArrayList;  8 import java.util.List;  9  10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12  13 import jxl.Workbook; 14 import jxl.write.Label; 15 import jxl.write.WritableFont; 16 import jxl.write.WritableSheet; 17 import jxl.write.WritableWorkbook; 18  19 import org.apache.struts2.ServletActionContext; 20  21 import com.lowagie.text.Document; 22 import com.lowagie.text.Element; 23 import com.lowagie.text.Font; 24 import com.lowagie.text.PageSize; 25 import com.lowagie.text.Paragraph; 26 import com.lowagie.text.pdf.PdfPTable; 27 import com.lowagie.text.pdf.PdfWriter; 28 import com.opensymphony.xwork2.Action; 29  30 public class downloadAction implements Action { 31  32     private String downType; 33  34     public String getDownType() { 35         return downType; 36     } 37  38     public void setDownType(String downType) { 39         this.downType = downType; 40     } 41  42     public String execute() { 43         // TODO Auto-generated method stub 44         HttpServletRequest request = ServletActionContext.getRequest(); 45         //HttpServletResponse response = ServletActionContext.getResponse(); 46         //此处模拟数据库读出的数据。在真正的项目中。我们可以通过在session中保存的前端数据集合替换这里 47         List<Person> list = new ArrayList<Person>(); 48         for (int i = 1; i < 6; i++) { 49             Person person = new Person(); 50             person.setId(String.valueOf(i)); 51             person.setName(String.valueOf((char) (i + 64))); 52             person.setAge(i + 20); 53             person.setSex("man"); 54             list.add(person); 55         } 56         OutputStream os = null; 57         String fname = "personlist"; 58         if ("PDF".equals(downType)) { 59             try { 60             //    response.reset(); 61             //    os = response.getOutputStream(); 62                 FileOutputStream out = new FileOutputStream("d://a.pdf"); 63                 Document document = new Document(PageSize.A4, 50, 50, 50, 50); 64             //    response.setContentType("application/pdf"); 65             //    response.setHeader("Content-disposition", 66             //            "attachment;filename=" + fname + ".pdf"); 67                 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 68  69                 PdfWriter.getInstance(document, out); 70                 document.open(); 71                 int cols = list.size(); 72                 // 创建PDF表格 73                 PdfPTable table = new PdfPTable(4); 74                 // 设置pdf表格的宽度 75                 table.setTotalWidth(500); 76                 // 设置是否要固定其宽度 77                 table.setLockedWidth(true); 78                 // 表头字体 79                 Font thfont = new Font(); 80                 // 设置表头字体的大小 81                 thfont.setSize(7); 82                 // 设置表头字体的样式 83                 thfont.setStyle(Font.BOLD); 84                 Font tdfont = new Font(); 85                 tdfont.setSize(7); 86                 tdfont.setStyle(Font.NORMAL); 87                 // 设置水平对齐方式 88                 table.setHorizontalAlignment(Element.ALIGN_MIDDLE); 89                 // 设置table的header 90                 table.addCell(new Paragraph("id", thfont)); 91                 table.addCell(new Paragraph("name", thfont)); 92                 table.addCell(new Paragraph("sex", thfont)); 93                 table.addCell(new Paragraph("age", thfont)); 94                 // 循环设置table的每一行 95                 for (int i = 0; i < list.size(); i++) { 96                     Person p = (Person) list.get(i); 97                     table.addCell(new Paragraph(p.getId(), tdfont)); 98                     table.addCell(new Paragraph(p.getName(), tdfont)); 99                     table.addCell(new Paragraph(p.getSex(), tdfont));100                     table.addCell(new Paragraph(String.valueOf(p.getAge()),101                             tdfont));102                 }103                 document.add(table);104                 document.close();105             //    baos.writeTo(response.getOutputStream());106                 baos.close();107             } catch (Exception e) {108                 e.printStackTrace();109             }110         } else if ("CSV".equals(downType)) {111         //    response.reset();112             // 生成csv文件113             //response.setHeader("Content-disposition", "attachment;filename="114             //        + fname + ".csv");115             //response.setContentType("text/csv");116             //response.setCharacterEncoding("UTF-8");117             FileOutputStream out ;118             String sep = ",";119             try {120                 out = new FileOutputStream(new File("d://a.cvs"));121                 //out = response.getOutputStream();122                 out.write("id".getBytes());123                 out.write(sep.getBytes());124                 out.write("name".getBytes());125                 out.write(sep.getBytes());126                 out.write("sex".getBytes());127                 out.write(sep.getBytes());128                 out.write("age".getBytes());129                 out.write(sep.getBytes());130                 out.write(System.getProperty("line.separator").getBytes());131                 for (int i = 0; i < list.size(); i++) {132                     Person p = (Person) list.get(i);133                     out.write(p.getId().getBytes());134                     out.write((sep + "/t").getBytes());135                     out.write(p.getName().getBytes());136                     out.write((sep + "/t").getBytes());137                     out.write(p.getSex().getBytes());138                     out.write((sep + "/t").getBytes());139                     out.write(String.valueOf(p.getAge()).getBytes());140                     out.write((sep + "/t").getBytes());141                     out.write(sep.getBytes());142                     out.write(System.getProperty("line.separator").getBytes());143                 }144                 out.flush();145                 //out.cloute();146             } catch (Exception e) {147                 e.printStackTrace();148             }149         } else if (downType.equals("Excel")) {150             //response.reset();151             // 生成xls文件152             //response.setContentType("application/vnd.ms-excel");153             //response.setHeader("Content-disposition", "attachment;filename="154             //        + fname + ".xls");155             try {156                 //os = response.getOutputStream();157                 Label l = null;158                 WritableWorkbook wbook = Workbook.createWorkbook(new File(159                         "d://a.xls"));160                 // 写sheet名称161                 WritableSheet sheet = wbook.createSheet("my excel file", 0);162                 jxl.write.WritableFont wfc4 = new jxl.write.WritableFont(163                         WritableFont.ARIAL, 9, WritableFont.NO_BOLD, false,164                         jxl.format.UnderlineStyle.NO_UNDERLINE,165                         jxl.format.Colour.BLACK);166                 jxl.write.WritableCellFormat wcfFC4 = new jxl.write.WritableCellFormat(167                         wfc4);168                 wcfFC4.setBackground(jxl.format.Colour.LIGHT_GREEN);169                 int col = 0;170                 sheet.setColumnView(col, 12);171                 l = new Label(col, 0, "id", wcfFC4);172                 sheet.addCell(l);173                 col++;174                 sheet.setColumnView(col, 12);175                 l = new Label(col, 0, "name", wcfFC4);176                 sheet.addCell(l);177                 col++;178                 sheet.setColumnView(col, 12);179                 l = new Label(col, 0, "sex", wcfFC4);180                 sheet.addCell(l);181                 col++;182                 sheet.setColumnView(col, 12);183                 l = new Label(col, 0, "age", wcfFC4);184                 sheet.addCell(l);185 186                 // 设置字体样式187                 jxl.write.WritableFont wfc5 = new jxl.write.WritableFont(188                         WritableFont.ARIAL, 9, WritableFont.NO_BOLD, false,189                         jxl.format.UnderlineStyle.NO_UNDERLINE,190                         jxl.format.Colour.BLACK);191                 jxl.write.WritableCellFormat wcfFC5 = new jxl.write.WritableCellFormat(192                         wfc5);193                 for (int i = 0; i < list.size(); i++) {194                     Person p = (Person) list.get(i);195                     int j = 0;196                     l = new Label(j, i + 1, p.getId(), wcfFC5);197                     sheet.addCell(l);198                     j++;199                     l = new Label(j, i + 1, p.getName(), wcfFC5);200                     sheet.addCell(l);201                     j++;202                     l = new Label(j, i + 1, p.getSex(), wcfFC5);203                     sheet.addCell(l);204                     j++;205                     l = new Label(j, i + 1, String.valueOf(p.getAge()), wcfFC5);206                     sheet.addCell(l);207                     j++;208                 }209                 // 写入流中210                 wbook.write();211                 wbook.close();212 213             } catch (Exception e) {214                 e.printStackTrace();215             }216         }217         return SUCCESS;218     }219     }220     
复制代码

操作很简单。选择好要导出的报表格式。点击导出按钮。我们在d盘相应的位置就会生成相应的报表。

0 0