java操作office和pdf文件頁面列表導出cvs,excel、pdf報表.

 

        在平常的開發中我們常常遇到不僅僅只是導出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盤相應的位置就會生成相應的報表。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章