標籤:filename setborder style position chm span writable font ddc
本篇文章基於java把資料庫中的資料以Excel的方式匯出,歡迎各位大神吐槽:
1、基於maven jar包引入如下:
1 <dependency>2 <groupId>net.sourceforge.jexcelapi</groupId>3 <artifactId>jxl</artifactId>4 <version>2.6.12</version>5 </dependency>
2、首先建立資料庫對應的實體類VO :UserVO(具體代碼省略);
3、確定匯出Excel內的title列,並放在數組裡:String[] (具體代碼省略);
4、編寫匯出Excel的方法:
傳入參數:
Excel名稱,Excel內的title列數組String[],資料集合List<UserVO>
1 package bp.util; 2 3 import java.io.OutputStream; 4 import java.util.List; 5 import javax.servlet.http.HttpServletResponse; 6 import java.lang.reflect.Field; 7 8 import jxl.Workbook; 9 import jxl.format.Alignment;10 import jxl.format.Border;11 import jxl.format.BorderLineStyle;12 import jxl.format.VerticalAlignment;13 import jxl.write.Label;14 import jxl.write.WritableCellFormat;15 import jxl.write.WritableFont;16 import jxl.write.WritableSheet;17 import jxl.write.WritableWorkbook;18 19 public class ExportExcel {20 21 public final static String exportExcel(String fileName, String[] Title, List listContent,22 HttpServletResponse response) {23 String result = "Excel檔案匯出成功!";24 try {25 OutputStream os = response.getOutputStream();26 response.reset();27 response.setHeader("Content-disposition",28 "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));29 response.setContentType("application/msexcel");30 WritableWorkbook workbook = Workbook.createWorkbook(os);31 32 WritableSheet sheet = workbook.createSheet("Sheet1", 0);33 jxl.SheetSettings sheetset = sheet.getSettings();34 sheetset.setProtected(false);35 36 WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);37 WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);38 wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN);39 wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE);40 wcf_center.setAlignment(Alignment.CENTRE);41 wcf_center.setWrap(true);42 43 for (int i = 0; i < Title.length; i++) {44 sheet.setColumnView(i, 20);45 sheet.addCell(new Label(i, 0, Title[i], wcf_center));46 }47 Field[] fields = null;48 int i = 1;49 for (Object obj : listContent) {50 fields = obj.getClass().getDeclaredFields();51 int j = 0;52 for (Field v : fields) {53 v.setAccessible(true);54 Object va = v.get(obj);55 if (va == null) {56 va = "";57 }58 sheet.addCell(new Label(j, i, va.toString(), wcf_center));59 j++;60 }61 i++;62 }63 workbook.write();64 workbook.close();65 66 } catch (Exception e) {67 result = "Excel檔案匯出失敗";68 e.printStackTrace();69 }70 return result;71 }72 }
在需要匯出資料的時候調用此方法即可;
java 匯出excel表格式資料