标签: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 }
在需要导出数据的时候调用此方法即可;
标签:filename setborder style position chm span writable font ddc
原文地址:http://www.cnblogs.com/bestxyl/p/7383103.html