package com.lenovo.cochat.utils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.io.*; import java.util.*; import static com.lenovo.cochat.utils.DateUtil.*; public class NewExcelUtil { private HSSFWorkbook workbook; private HSSFSheet sheet; /** * 创建行元素 * @param style 样式 * @param height 行高 * @param value 行显示的内容 * @param row1 起始行 * @param row2 结束行 * @param col1 起始列 * @param col2 结束列 */ private void createRow(HSSFCellStyle style, int height, String value, int row1, int row2, int col1, int col2){ sheet.addMergedRegion(new CellRangeAddress(row1, row2, col1, col2)); //设置从第row1行合并到第row2行,第col1列合并到col2列 HSSFRow rows = sheet.createRow(row1); //设置第几行 rows.setHeight((short) height); //设置行高 HSSFCell cell = rows.createCell(col1); //设置内容开始的列 cell.setCellStyle(style); //设置样式 cell.setCellValue(value); //设置该行的值 } private void createRow1( int row1, int row2, int col1, int col2){ sheet.addMergedRegion(new CellRangeAddress(row1, row2, col1, col2)); //设置从第row1行合并到第row2行,第col1列合并到col2列 HSSFRow rows = sheet.createRow(row1); //设置第几行 rows.setHeight((short) 80); //设置行高 HSSFCellStyle style = workbook.createCellStyle(); style.setBorderBottom(BorderStyle.valueOf((short) 2)); style.setBorderTop(BorderStyle.valueOf((short) 2)); for (int i = 0; i < col2+1; i++) { HSSFCell cell = rows.createCell(i); cell.setCellStyle(style); } } /** * 创建样式 * @param fontSize 字体大小 * @param align 水平位置 左右居中2 居右3 默认居左 垂直均为居中 * @param bold 是否加粗 * @return */ private HSSFCellStyle getStyle(int fontSize,int align,boolean bold,boolean border){ HSSFFont font = workbook.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) fontSize);// 字体大小 if (bold){ font.setBold(true); } HSSFCellStyle style = workbook.createCellStyle(); style.setFont(font); //设置字体 style.setAlignment(HorizontalAlignment.forInt((short) align)); // 左右居中2 居右3 默认居左 style.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中1 if (border){ style.setBorderRight(BorderStyle.valueOf((short) 2)); style.setBorderLeft(BorderStyle.valueOf((short) 2)); style.setBorderBottom(BorderStyle.valueOf((short) 2)); style.setBorderTop(BorderStyle.valueOf((short) 2)); style.setLocked(true); } return style; } /** * 根据数据集生成Excel,并返回Excel文件流 * @param data 数据集 * @param sheetName Excel中sheet单元名称 * @param headNames 列表头名称数组 * @param colKeys 列key,数据集根据该key进行按顺序取值 * @return * @throws IOException */ public InputStream getExcelFile(List<List<Map>> data, String sheetName, List<String> headNames, String[] colKeys, int colWidths[]) {
java poi 操作自定义excel(修改下载路径可以直接使用)
最新推荐文章于 2021-12-17 17:36:02 发布