weaver-hrm-salary/src/com/engine/salary/util/excel/ExcelUtil.java

65 lines
2.4 KiB
Java
Raw Normal View History

2022-03-10 11:09:08 +08:00
package com.engine.salary.util.excel;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import java.util.List;
public class ExcelUtil {
/**
* 生成excel
* @param rowList
* @return
*/
2022-03-10 17:57:46 +08:00
public static XSSFWorkbook genWorkbook(List<List<String>> rowList,String sheetName) {
2022-03-10 11:09:08 +08:00
XSSFWorkbook workbook = new XSSFWorkbook();
// 设置title样式
XSSFCellStyle titleCellStyle = workbook.createCellStyle();
XSSFFont titleFont = workbook.createFont();
titleFont.setFontName("仿宋");
titleFont.setFontHeightInPoints((short) 15);
titleCellStyle.setFont(titleFont);
titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
titleCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());//背景色
titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置主体样式
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);// 设置字体大小
cellStyle.setFont(font);// 选择需要用到的字体格式
cellStyle.setWrapText(true);
2022-03-10 17:57:46 +08:00
XSSFSheet sheet = workbook.createSheet(sheetName);
2022-03-10 11:09:08 +08:00
//自适应宽度
sheet.autoSizeColumn(0, true);
//默认列宽
sheet.setDefaultColumnWidth(20);
//默认行高
sheet.setDefaultRowHeightInPoints(18);
for (int rowIndex = 0; rowIndex < rowList.size(); rowIndex++) {
List<String> infoList = rowList.get(rowIndex);
XSSFRow row = sheet.createRow(rowIndex);
for (int cellIndex = 0; cellIndex < infoList.size(); cellIndex++) {
XSSFCell cell = row.createCell(cellIndex);
cell.setCellType(CellType.STRING);
if (rowIndex == 0) {
cell.setCellStyle(titleCellStyle);
} else {
cell.setCellStyle(cellStyle);
}
cell.setCellValue(infoList.get(cellIndex));
// sheet.setColumnWidth(cellIndex, 35 * 256);
}
}
return workbook;
}
}