1.首先获取Excel模板的路径,本例放在了项目中
String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "templetfile" + File.separator; String filename = "rolledlossData.xlsx";
2.获取XSSFWorkbook对象(XSSFWorkbook是操作Excel2007的版本,扩展名是.xlsx)
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(path+filename));
3.获取要导出的对象集合(对象属性要与表格中顺序、字段完全相同)
-----------本例中使用List<Object> list
4.将对象集合写到excel表中
Workbook wb =hssfWorkbook; Sheet sheet = wb.getSheetAt(0); Row row = null; Cell cell; Object data = null; Object fieldValue = null; SimpleDateFormat format = new SimpleDateFormat(defaultDateFormatPattern); /** 写数据到excel **/ CellStyle dataStyle = createDataCellStyle(wb); Field[] fields = list.get(0).getClass().getDeclaredFields(); int sums = list.size(); for (int rowIndex = 0; rowIndex < sums; rowIndex++) { data = list.get(rowIndex); row = sheet.createRow(rowIndex + 1); int colums = fields.length; for (int i=0;i<colums;i++){ cell = row.createCell(i); cell.setCellStyle(dataStyle); fieldValue = ReflectiveUtils.getValueByReflectField(data, fields[i]); cell.setCellValue(convertObjectToString(fieldValue, format)); } }
通过反射获取属性的值,并把属性值转换为 String 类型的方法
public static Object getValueByReflectField(Object data, Field field) { try { if(field == null){ return null; } field.setAccessible(true); Object value = field.get(data); return value; } catch (SecurityException e) { logger.error("通过反射获取类属性失败",e); throw new RuntimeException("通过反射获取类属性失败",e); }catch (IllegalArgumentException e) { logger.error("通过反射获取对象值时,对象不合法",e); throw new RuntimeException("通过反射获取对象值时,对象不合法",e); } catch (IllegalAccessException e) { logger.error("无法通过反射获取对象值,权限不足",e); throw new RuntimeException("无法通过反射获取对象值,权限不足",e); } }
把对象转为String的方法
private static String convertObjectToString(Object value, DateFormat format) { String strValue = null; if (value instanceof Date) { strValue = format.format(value); } else if (value instanceof String) { strValue = (String) value; } else { if (value == null) { strValue = ""; } else { strValue = value.toString(); } } return strValue; }
5.将表格写入到流中
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); wb.write(byteOutput); InputStream inputStream = new ByteArrayInputStream( byteOutput.toByteArray());
6.把文件流写到客户端(其中response为客户端请求HttpServletResponse response)
BufferedInputStream bin = null; BufferedOutputStream bos = null; GZIPOutputStream gzipOutput = null; try { /** 这里把文件名转换,否则中文乱码 **/ String fileName = new String(displayName.getBytes("GBK"),"ISO-8859-1"); // 清空response response.reset(); //客服端使用保存文件的对话框 response.setHeader("Content-disposition", "attachment;filename="+fileName); response.setHeader("Content-Encoding", "gzip"); response.setContentType("application/octet-stream"); bin = new BufferedInputStream(inputStream); OutputStream out = response.getOutputStream(); bos = new BufferedOutputStream(out); /** 这里使用gizp进行压缩 **/ gzipOutput = new GZIPOutputStream(bos); byte[] buffer = new byte[512]; int readCount = -1; while(true){ readCount = bin.read(buffer); if(readCount == -1){ break; } gzipOutput.write(buffer,0,readCount); } }finally{ if(bin != null){ bin.close(); } if(gzipOutput != null){ gzipOutput.close(); } }