一.导入依赖
<!-- poi导出excel所依赖的部分包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M2</version>
</dependency>
二.样式设置
//设置单元格背景颜色
Sheet sheet=workbook.getSheetAt(0);
Row row=sheet.getRow(0);
Cell cell=row.getCell(0);
CellStyle style = workbook.createCellStyle(); style.cloneStyleFrom(cell.getCellStyle()); //设置背景颜色 style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); //设置自动换行 style.setWrapText(true); //设置字体样式
Font font= row.getSheet().getWorkbook().createFont(); //默认字体为宋体 font.setFontName("宋体");
//设置字体大小
font.setFontHeight((short) 18);
//设置字体颜色
font.setColor(IndexedColors.BLUE_GREY.getIndex());
//设置字体加粗
font.setBold(true);
//设置字体斜体
font.setItalic(true);
//设置字体下划线
font.setUnderline(Font.U_SINGLE); //设置字体上标下标 font.setTypeOffset(Font.SS_SUPER);
//设置字体删除线
font.setStrikeout(true);
style.setFont(font);
//边框样式
//设置上边框线条类型
style.setBorderTop(BorderStyle.THIN);
//设置右边框线条类型
style.setBorderRight(BorderStyle.THIN);
//设置下边框线条类型
style.setBorderBottom(BorderStyle.THIN);
//设置左边框线条类型
style.setBorderLeft(BorderStyle.THIN);
//设置上边框线条颜色
style.setTopBorderColor(IndexedColors.BLUE_GREY.getIndex());
//设置右边框线条颜色
style.setRightBorderColor(IndexedColors.BLUE_GREY.getIndex());
//设置下边框线条颜色
style.setBottomBorderColor(IndexedColors.BLUE_GREY.getIndex());
//设置左边框线条颜色
style.setLeftBorderColor(IndexedColors.BLUE_GREY.getIndex());
//对齐方式
//设置水平对齐方式
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐方式
style.setVerticalAlignment(VerticalAlignment.CENTER);
自适应宽度或者设置宽度
//设置列宽行高
//设置自适应列宽
sheet.setDefaultColumnWidth(0);
//自定义列宽
sheet.setColumnWidth(0,10);
//自定义行高
row.setHeight((short)10);
手动对列设置自适应宽度
private void setSizeColumn(Sheet sheet,int columnNum) {
//当前列宽度
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
//获取最后一行(总行数)
int lastRowNum = sheet.getLastRowNum();
//找到宽度最大值
for (int i = 0; i <lastRowNum ; i++) {
Row row = sheet.getRow(i);
if (ObjectUtil.isNotNull(row)){
Cell cell=row.getCell(columnNum);
//数据类型为字符串
if (cell.getCellType()== CellType.STRING){
int length = cell.getStringCellValue().getBytes().length;
//获取最大值
columnWidth=Math.max(length,columnWidth);
}
}
}
sheet.setColumnWidth(columnNum, columnWidth*256>=256*256?200*256:columnWidth*256);
}