簡單Java實現Excel文件導出
Java導出要在action層(controller層)中操作
需要到的jar包:
後端代碼:
後面兩個函數都是設置Excel文件裏的標題樣式,專注第一個方法就可以了
/**
* 導出房產信息
* @param fcHouseProMain
* @param request
* @param response
* @param redirectAttributes
* @return
*/
@RequiresPermissions("housepro:fcHouseProMain:view")
@RequestMapping(value = "export", method=RequestMethod.POST)
public String exportFile(FcHouseProMain fcHouseProMain, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = "房產信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
/*List<FcHouseProMain> list = fcHouseProMainService.findList(fcHouseProMain);
new ExportExcel("房產信息", FcHouseProMain.class).setDataList(list).write(response, fileName).dispose();*/
SXSSFWorkbook wb = new SXSSFWorkbook(500);
Sheet sheet = wb.createSheet("Export");
Map<String, CellStyle> styles = createStyles(wb);
String str[] = {"ID","名稱"};
initialize("房產信息",Arrays.asList(str),wb,sheet,styles);
for (int i = 0; i <2; i++) {
Row row = sheet.createRow(rownum++);
Cell ce1 = row.createCell(0);
ce1.setCellValue("100"+(i+1));
Cell ce2 = row.createCell(1);
ce2.setCellValue("張三"+(i+1));
}
OutputStream out = response.getOutputStream();
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
wb.write(out);
wb.dispose();
out.flush();
out.close();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "導出房產信息失敗!失敗信息:"+e.getMessage());
}
return "redirect:"+Global.getAdminPath()+"/housepro/fcHouseProMain/?repage";
}
/**
* 當前行號
*/
private int rownum;
private void initialize(String title, List<String> headerList,SXSSFWorkbook wb,Sheet sheet,Map<String, CellStyle> styles) {
// Create title
if (StringUtils.isNotBlank(title)){
Row titleRow = sheet.createRow(rownum++);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
}
// Create header
if (headerList == null){
throw new RuntimeException("headerList not null!");
}
Row headerRow = sheet.createRow(rownum++);
headerRow.setHeightInPoints(16);
for (int i = 0; i < headerList.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header"));
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
if (ss.length==2){
cell.setCellValue(ss[0]);
Comment comment = sheet.createDrawingPatriarch().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
comment.setString(new XSSFRichTextString(ss[1]));
cell.setCellComment(comment);
}else{
cell.setCellValue(headerList.get(i));
}
sheet.autoSizeColumn(i);
}
for (int i = 0; i < headerList.size(); i++) {
int colWidth = sheet.getColumnWidth(i)*2;
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
}
}
/**
* 創建表格樣式
* @param wb 工作薄對象
* @return 樣式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
Font titleFont = wb.createFont();
titleFont.setFontName("Arial");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(titleFont);
styles.put("title", style);
style = wb.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = wb.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
style.setFont(dataFont);
styles.put("data", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_LEFT);
styles.put("data1", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("data2", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
style.setAlignment(CellStyle.ALIGN_RIGHT);
styles.put("data3", style);
style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data"));
// style.setWrapText(true);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font headerFont = wb.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setColor(IndexedColors.WHITE.getIndex());
style.setFont(headerFont);
styles.put("header", style);
return styles;
}