1. First get the path of the Excel template, this example is placed in the project
String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "templetfile" + File.separator; String filename = "rolledlossData.xlsx";
2. Get the XSSFWorkbook object ( XSSFWorkbook is the version that operates Excel2007, the extension is .xlsx)
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(path+filename));
3. Get the set of objects to be exported (the object properties must be in the same order and fields as in the table)
------------- List<Object> list is used in this example
4. Write the object collection to the excel sheet
Workbook wb =hssfWorkbook; Sheet sheet = wb.getSheetAt(0); Row row = null; Cell cell; Object data = null; Object fieldValue = null; SimpleDateFormat format = new SimpleDateFormat(defaultDateFormatPattern); /** write data to 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)); } }
Get the value of the attribute through reflection, and convert the attribute value to String type method
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("Failed to obtain class attributes through reflection",e); throw new RuntimeException("Failed to obtain class attributes through reflection",e); }catch (IllegalArgumentException e) { logger.error("Acquired through reflection When the object value is used, the object is invalid",e); throw new RuntimeException("When the object value is obtained by reflection, the object is invalid",e); } catch (IllegalAccessException e) { logger.error("The object value cannot be obtained by reflection , insufficient permissions",e); throw new RuntimeException("Cannot get the object value through reflection, insufficient permissions",e); } }
How to convert object to 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. Write the table to the stream
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); wb.write(byteOutput); InputStream inputStream = new ByteArrayInputStream( byteOutput.toByteArray());
6. Write the file stream to the client (where the response is the client request HttpServletResponse response)
BufferedInputStream bin = null; BufferedOutputStream bos = null; GZIPOutputStream gzipOutput = null; try { /** Convert the file name here, otherwise Chinese garbled **/ String fileName = new String(displayName.getBytes("GBK"),"ISO-8859-1"); // clear the response response.reset(); //The client side uses the dialog box to save the file 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); /** This uses gizp for compression**/ 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(); } }