1 package com.cdsxt.util; 2 3 import java.lang.reflect.Method; 4 import java.util.Date; 5 import java.util.List; 6 7 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 8 import org.apache.poi.ss.usermodel.Cell; 9 import org.apache.poi.ss.usermodel.CellStyle; 10 import org.apache.poi.ss.usermodel.CreationHelper; 11 import org.apache.poi.ss.usermodel.HorizontalAlignment; 12 import org.apache.poi.ss.usermodel.Row; 13 import org.apache.poi.ss.usermodel.Sheet; 14 import org.apache.poi.ss.usermodel.VerticalAlignment; 15 import org.apache.poi.ss.usermodel.Workbook; 16 import org.apache.poi.ss.util.CellRangeAddress; 17 18 public class ExcelUtil { 19 20 /** 21 * 22 * 23 * @param title 标题 24 * @param headers key:label 进行执行 key 需要导出的列名或是属性名 label显示的中文名称 25 * @param data 数据 26 * @return 27 */ 28 public staticWorkbook export(String title,String []headers,List data){ 29 30 if(!(title!=null && title.length()>0)){ 31 title = "详细信息"; 32 } 33 34 if(headers==null){ 35 throw new IllegalArgumentException("headers不能为空"); 36 } 37 38 Workbook wb = new HSSFWorkbook(); 39 CreationHelper helper = wb.getCreationHelper(); 40 Sheet sheet = wb.createSheet("Sheet 1"); 41 dealTitle(sheet, wb.createCellStyle(), title, headers.length-1); 42 43 44 //处理表头数据 45 dealHeaders(sheet,wb.createCellStyle(),headers); 46 47 //处理数据 48 //如果 data没有数据 或者是null 则可以在excel中写出一行为 暂无数据 49 if(data!=null && !data.isEmpty()){ 50 //得到字节码 51 Class clazz = data.get(0).getClass(); 52 53 //处理数据 54 for(int i=0;i
以上是excel导出的工具类,以下是具体用法:前台ajax请求过来
1 @RequestMapping("/export.do") 2 @ResponseBody 3 public String export(){ 4 ListclientList = clientService.findAll(); 5 Workbook wb = ExcelUtil.export("客户信息", new String[] 6 {"cid:客户编号","cname:客户名称","legalPerson:法人代表","city:城市", 7 "regisTime:登记时间","email:邮箱","belonger:所属人员","grade:等级"}, clientList); 8 try { 9 wb.write(new FileOutputStream("F:/client.xls"));10 wb.close();11 } catch (FileNotFoundException e) {12 e.printStackTrace();13 } catch (IOException e) {14 e.printStackTrace();15 } 16 return "";17 }
具体效果如下