import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import org.apache.poi.xssf.usermodel.*; public class ExportExcel<T> { public void exportExcel(String[] headers, Collection<T> dataset, String fileName, HttpServletResponse response) { // 聲明一個工作薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個表格 XSSFSheet sheet = workbook.createSheet(fileName); // 設置表格默認列寬度爲15個字節 sheet.setDefaultColumnWidth((short) 20); // 產生表格標題行 XSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { XSSFCell cell = row.createCell(i); XSSFRichTextString text = new XSSFRichTextString(headers[i]); cell.setCellValue(text); } try { // 遍歷集合數據,產生數據行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); // 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值 Field[] fields = t.getClass().getDeclaredFields(); for (short i = 0; i < headers.length; i++) { XSSFCell cell = row.createCell(i); Field field = fields[i]; String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 判斷值的類型後進行強制類型轉換 String textValue = null; // 其它數據類型都當作字符串簡單處理 if(value != null && value != ""){ textValue = value.toString(); } if (textValue != null) { XSSFRichTextString richString = new XSSFRichTextString(textValue); cell.setCellValue(richString); } } } getExportedFile(workbook, fileName,response); } catch (Exception e) { e.printStackTrace(); } } /** * * 方法說明: 指定路徑下生成EXCEL文件 * @return */ public void getExportedFile(XSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception { BufferedOutputStream fos = null; try { String fileName = name + ".xlsx"; response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" )); fos = new BufferedOutputStream(response.getOutputStream()); workbook.write(fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { fos.close(); } } } }
springMVC 使用
@RequestMapping("/outputexcel") public void export(HttpServletResponse response) throws Exception { Map<String,Object> map = new HashMap<String,Object>(); List<user> userlList = userService.queryuserAll(); ExportExcel<user> ee= new ExportExcel<user>(); String[] headers = { "姓名","性別","身份證號","出生日期"}; String fileName = "用戶信息表"; ee.exportExcel(headers,userlList,fileName,response); }