依赖: org.apache.poi poi-ooxml 3.15-beta2 org.apache.poi poi-ooxml-schemas 3.17
核心代码:
/**
* title:导出excel标题、headers 导出到excel显示的列头、 columns 对应数据库字段 、list 导出数据
* @param title
* @param headers
* @param columns
* @param list
* @param out
* @param pattern
* @throws NoSuchMethodException
* @throws Exception
*/
public void expoortExcelx(String title, String[] headers, String[] columns,
List list, OutputStream out, String pattern) throws NoSuchMethodException, Exception{
//创建工作薄
XSSFWorkbook workbook=new XSSFWorkbook();
//创建表格
Sheet sheet=workbook.createSheet(title);
//设置默认宽度
sheet.setDefaultColumnWidth(25);
//创建样式
XSSFCellStyle style=workbook.createCellStyle();
//设置样式
style.setFillForegroundColor(IndexedColors.GOLD.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
//生成字体
XSSFFont font=workbook.createFont();
font.setColor(IndexedColors.VIOLET.index);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
//应用字体
style.setFont(font);
//自动换行
style.setWrapText(true);
//声明一个画图的顶级管理器
Drawing drawing=(XSSFDrawing) sheet.createDrawingPatriarch();
//表头的样式
XSSFCellStyle titleStyle=workbook.createCellStyle();//样式对象
titleStyle.setAlignment(CellStyle.ALIGN_CENTER_SELECTION);//水平居中
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
//设置字体
XSSFFont titleFont=workbook.createFont();
titleFont.setFontHeightInPoints((short)15);
titleFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);//粗体
titleStyle.setFont(titleFont);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length-1));
//指定合并区域
Row rowHeader = sheet.createRow(0);
//XSSFRow rowHeader=sheet.createRow(0);
Cell cellHeader=rowHeader.createCell(0);
XSSFRichTextString textHeader=new XSSFRichTextString(title);
cellHeader.setCellStyle(titleStyle);
cellHeader.setCellValue(textHeader);
Row row=sheet.createRow(1);
for(int i=0;i0){
int index=2;
for(GrApplyDetails t:list){
row=sheet.createRow(index);
index++;
for(short i=0;i |