excel工具类ExcelUtils

本文代码来源于项目中的积累整理。

public class ExcelUtils {private static Logger log = LoggerFactory.getLogger(ExcelReader.class);private final static String RSPAN = "#rspan";//合并列空格占位private final static String CSPAN = "#cspan";//合并行空格占位/*** 创建简单的Excel* @param title 文件名和sheet名* @param columnTitles Excel表头* @param data Excel数据* @return* @throws Exception*/@SuppressWarnings("rawtypes")public static File simpleCreate(String title, String[] columnTitles, Collection data) throws Exception {return simpleCreate(title, columnTitles, data, null, null);}/*** 创建简单的Excel* @param title 文件名和sheet名* @param columnTitles Excel表头* @param data Excel数据* @param rowCelIndexList 行列索引集合 List<List<int[]>> int[0] 行索引, int[1] 列索引* @param backgroudColrList 背景颜色 List<颜色代码(如HSSFColor.GREY_25_PERCENT.index)>* @return* @throws Exception*/@SuppressWarnings("rawtypes")public static File simpleCreate(String title, String[] columnTitles, Collection data, List<List<int[]>> rowCelIndexList, List<Short> backgroudColrList) throws Exception {File file = null;HSSFWorkbook book = null;FileOutputStream fis = null;try {String path = ExcelUtils.class.getClassLoader().getResource("/").getPath() + title + ".xls";path = path.replace("%20", " ");file = new File(path);book = new HSSFWorkbook();createSheets(title, columnTitles, data, book);fis = new FileOutputStream(file);HSSFSheet sheet = book.getSheetAt(0);setCellBackgroundColor(sheet, rowCelIndexList, backgroudColrList);book.write(fis);fis.flush();return file;} catch (Exception e) {log.error("", e);throw e;} finally {if (fis != null) {fis.close();}}}/*** 创建sheet* @param sheetName* @param columnTitles* @param data* @param book*/@SuppressWarnings("rawtypes")private static void createSheets(String sheetName, String[] columnTitles, Collection data, HSSFWorkbook book) {HSSFSheet sheet = book.createSheet(sheetName);HSSFCellStyle titleCellStyle = getTitleCellStyle(book);HSSFCellStyle cellStyle = getCellStyle(book);Cell cell = null;// 如果表头不为空,则写入表头Row excelRow = null;if (columnTitles != null) {excelRow = sheet.createRow(0);for (int i = 0; i < columnTitles.length; i++) {cell = excelRow.createCell(i);initCell(cell, columnTitles[i], titleCellStyle);}}// 写入数据int rowIndex = 1;Iterator it = data.iterator();while (it.hasNext()) {Object[] row = (Object[]) it.next();excelRow = sheet.createRow(rowIndex++);int colIndex = 0;for (Object cellValue : row) {cell = excelRow.createCell(colIndex);setColumnWidth(sheet, colIndex, cellValue);initCell(cell, cellValue, cellStyle);colIndex++;}}}/*** 创建多个sheet的Excel表格* @param title Excel文件名* @param sheetNames sheet名称* @param columnTitleList 列名* @param dataList  表格数据* @return*/@SuppressWarnings("rawtypes")public static File anySheetsCreate(String title,String[] sheetNames,List<String[]> columnTitleList, List<Collection> dataList){File file = null;HSSFWorkbook book = null;FileOutputStream fis = null;try {String path = ExcelUtils.class.getClassLoader().getResource("/").getPath() + title + ".xls";path = path.replace("%20", " ");file = new File(path);book = new HSSFWorkbook();if(sheetNames!=null){for (int i = 0; i < sheetNames.length; i++) {createSheets(sheetNames[i], columnTitleList.get(i), dataList.get(i), book);}}fis = new FileOutputStream(file);book.write(fis);fis.flush();} catch (Exception e) {log.error("",e);} finally {if (fis != null) {try {fis.close();} catch (IOException e) {log.error("",e);}}}return file;}/*** 创建多个sheet的Excel表格,文件名自己定* @param title Excel文件名* @param sheetNames sheet名称* @param columnTitleList 列名* @param dataList  表格数据* @return*/@SuppressWarnings("rawtypes")public static File anySheetsCreate2(String path,String[] sheetNames,List<String[]> columnTitleList, List<Collection> dataList){File file = null;HSSFWorkbook book = null;FileOutputStream fis = null;try {path = path + ".xls";path = path.replace("%20", " ");file = new File(path);book = new HSSFWorkbook();if(sheetNames!=null){for (int i = 0; i < sheetNames.length; i++) {createSheets(sheetNames[i], columnTitleList.get(i), dataList.get(i), book);}}fis = new FileOutputStream(file);book.write(fis);fis.flush();} catch (Exception e) {log.error("",e);} finally {if (fis != null) {try {fis.close();} catch (IOException e) {log.error("",e);}}}return file;}/*** 创建多表头* @param title* @param mainTitleList 标题文字集合* @param footTitle 页脚文字* @param columnTitles 多表头* @param data 数据* @param configMap 配置信息, 可为空*          MainTitle1Style(主标题样式):宋体(字体样式),11(字体大小),right(对齐方式),20(行高),B(粗体)#I(斜体)#U(下划线)*          MainTitle2Style(副标题1样式)*          MainTitle3Style(副标题2样式)*          TitleStyle(表头样式)*          FootTitleStyle(页脚样式)*          DataStyle(数据样式):宋体(字体样式),11(字体大小),right(对齐方式),20(行高)*          DataWidth(数据宽度):20,10,25,30*          DataAlign(数据对齐方式):center,left,right,center* @return*/@SuppressWarnings("rawtypes")public static File mulitHeaderCreate(String title, List<String> mainTitleList, String footTitle, List<String[]> columnTitles, Collection data, Map<String, Object> configMap) {File file = null;HSSFWorkbook book = null;FileOutputStream fis = null;try {String path = ExcelUtils.class.getClassLoader().getResource("/").getPath() + title + ".xls";path = path.replace("%20", " ");file = new File(path);//file = new File("c://aaa.xls");book = new HSSFWorkbook();HSSFSheet sheet = book.createSheet(title);// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)int rowIndex = 0;Row excelRow = null;Cell cell = null;CellRangeAddress cra = null;HSSFCellStyle titleCellStyle = null;//15.625 表示行高为一个像素//35.7 表示宽度度为一个像素short h = (short) 15.625;// 如果表头不为空,则写入表头if (columnTitles != null) {String[] ttHeader = columnTitles.get(0);int columnLen = ttHeader.length; //列个数//添加主标题if (mainTitleList != null && !mainTitleList.isEmpty()) {for (int i=0; i<mainTitleList.size(); i++) {String titleStyle = (String) configMap.get("MainTitle" + (i+1) + "Style");titleCellStyle = getTitleCellStyle2(book, titleStyle);Integer titleHeight = ObjNumberUtils.toInteger(getConfigStr(titleStyle, 3));excelRow = sheet.createRow(rowIndex);if (titleHeight != null) {excelRow.setHeight((short) (h*titleHeight));}cra = new CellRangeAddress(rowIndex, rowIndex, 0, columnLen-1);sheet.addMergedRegion(cra);cell = excelRow.createCell(0);initCell(cell, mainTitleList.get(i), titleCellStyle);for (int j=1; j<=columnLen-1; j++) {cell = excelRow.createCell(j);initCell(cell, "", titleCellStyle);}rowIndex ++;}}String titleStyle = (String) configMap.get("TitleStyle");Integer titleHeight = ObjNumberUtils.toInteger(getConfigStr(titleStyle, 3));titleCellStyle = getTitleCellStyle(book, titleStyle);String dataWidthStr = (String) configMap.get("DataWidth");if (dataWidthStr != null && !"".equals(dataWidthStr)) {String[] dsArr = dataWidthStr.split(",");if (dsArr.length == columnLen) {//存在合并列,故dsArr.length <= columnLenint ssWidth = 0;for (int i=0; i<dsArr.length; i++) {ssWidth = ObjNumberUtils.toInt(dsArr[i]);if (ssWidth > 0) {sheet.setColumnWidth(i, Integer.parseInt(String.valueOf(Math.round(35.7*ssWidth))));//sheet.setColumnWidth(i, (int) (1*ssWidth));} else {sheet.setColumnWidth(i, (int) (35.7*120));}}}}// 当标题行只有一行时,不需要解析,直接顺序显示即可if (columnTitles.size() == 1) {String[] tempHeads = columnTitles.get(0);excelRow = sheet.createRow(rowIndex);if (titleHeight != null) {excelRow.setHeight((short) (h*titleHeight));}for (int i = 0; i < tempHeads.length; i++) {cell = excelRow.createCell(i);initCell(cell, tempHeads[i], titleCellStyle);}rowIndex++;} else {// 如果是多表头的时候,就需要解析合并表头int nextColIndex = 0;for (int i = 0; i < columnTitles.size(); i++) {excelRow = sheet.createRow(rowIndex);if (titleHeight != null) {excelRow.setHeight((short) (h*titleHeight));}String[] tempHeads = columnTitles.get(i);for (int j = 0; j < tempHeads.length; j++) {cell = excelRow.createCell(j);if (CSPAN.equals(tempHeads[j])) {int preColIndex = j - 1;preColIndex = preColIndex < 0 ? 0 : preColIndex;if (!CSPAN.equals(tempHeads[preColIndex])) {nextColIndex = j;while (nextColIndex < tempHeads.length && CSPAN.equals(tempHeads[nextColIndex])) {nextColIndex++;}cra = new CellRangeAddress(rowIndex+i, rowIndex+i, preColIndex, nextColIndex - 1);sheet.addMergedRegion(cra);initCell(cell, tempHeads[j], titleCellStyle);}else{initCell(cell, tempHeads[j], titleCellStyle);}} else if (RSPAN.equals(tempHeads[j])) {//合并列int preRowIndex = i - 1;preRowIndex = preRowIndex < 0 ? 0 : preRowIndex;if (!RSPAN.equals(columnTitles.get(preRowIndex)[j])) {int nextRowIndex = i;while (nextRowIndex < columnTitles.size() && RSPAN.equals(columnTitles.get(nextRowIndex)[j])) {nextRowIndex++;}cra = new CellRangeAddress(rowIndex+preRowIndex-1, rowIndex+nextRowIndex-2, j, j);sheet.addMergedRegion(cra);initCell(cell, tempHeads[j], titleCellStyle);}} else {initCell(cell, tempHeads[j], titleCellStyle);}}rowIndex++;}}}// 写入数据String dataConfigStr = (String) configMap.get("DataStyle");String dataFont = getConfigStr(dataConfigStr, 0);Integer dataFontSize = ObjNumberUtils.toInteger(getConfigStr(dataConfigStr, 1));Integer dataHeight = ObjNumberUtils.toInteger(getConfigStr(dataConfigStr, 3));String vertical = getConfigStr(dataConfigStr, 5);HSSFCellStyle dataCellStyle = null;Iterator it = data.iterator();dataCellStyle = getCellStyle(book, dataFont, dataFontSize, null);if(!StringUtils.isNullOrBlank(vertical) && NumberUtils.isNumber(vertical)){dataCellStyle.setVerticalAlignment(Short.parseShort(vertical));}while (it.hasNext()) {Object[] row = (Object[]) it.next();excelRow = sheet.createRow(rowIndex++);if (dataHeight != null) {excelRow.setHeight((short) (h*dataHeight));}int colIndex = 0;for (Object cellValue : row) {cell = excelRow.createCell(colIndex);initCell(cell, cellValue, dataCellStyle);colIndex++;}}if (columnTitles != null && footTitle != null && !"".equals(footTitle)) {String[] ttHeader = columnTitles.get(0);int columnLen = ttHeader.length; //列个数String footTitleStyle = (String) configMap.get("FootTitleStyle");titleCellStyle = getTitleCellStyle(book, footTitleStyle);//添加页脚Integer titleHeight = ObjNumberUtils.toInteger(getConfigStr(footTitleStyle, 3));excelRow = sheet.createRow(rowIndex);if (titleHeight != null) {excelRow.setHeight((short) (h*titleHeight));}cra = new CellRangeAddress(rowIndex, rowIndex, 0, columnLen-1);sheet.addMergedRegion(cra);cell = excelRow.createCell(0);initCell(cell, footTitle, titleCellStyle);for (int j=1; j<=columnLen-1; j++) {cell = excelRow.createCell(j);initCell(cell, "", titleCellStyle);}rowIndex ++;}fis = new FileOutputStream(file);book.write(fis);fis.flush();return file;} catch (Exception e) {e.printStackTrace();log.error("", e);} finally {if (fis != null) {try {fis.close();} catch (IOException e) {log.error("",e);}}}return file;}/*** 创建Excel单元格,根据数据的不同类型,创建不同类型的单元格* @param cell* @param value* @param cellStyle*/public static void initCell(Cell cell, Object value, HSSFCellStyle cellStyle) {if (cellStyle != null) {cell.setCellStyle(cellStyle);}if (value instanceof Number) {if (value != null) {cell.setCellValue(String.valueOf(value));}}if (value instanceof Date || value instanceof Timestamp || value instanceof java.sql.Date) {if (value != null) {cell.setCellValue(DateUtils.toString((Date) value));}}if (value instanceof String) {if (value != null) {cell.setCellValue(String.valueOf(value).trim());}}}/*** 根据数据的长度设置列的宽度*/public static void setColumnWidth(HSSFSheet sheet, int colIndex, Object value) {if (value == null) {return;}int minLen = 2800;int maxLen = 256 * 150;int len = (value.toString().getBytes().length+1) * 512;if (len < minLen) {len = minLen;}if(len > maxLen){len = maxLen;}//参数width的单位是1/256个字符宽度,设置宽度的时候,一个字符长度要乘以256sheet.setColumnWidth(colIndex, len);}/*** 设置单元格的背景颜色* @param sheet* @param rowCelIndexList* @param backgroudColrList*/private static void setCellBackgroundColor(HSSFSheet sheet, List<List<int[]>> rowCelIndexList, List<Short> backgroudColrList) {if (rowCelIndexList == null || rowCelIndexList.isEmpty() || backgroudColrList == null || backgroudColrList.isEmpty()) {return;}Cell cell = null;// 如果表头不为空,则写入表头Row excelRow = null;int i = 0;for (List<int[]> indexList : rowCelIndexList) {HSSFCellStyle style = getCellStyle(sheet.getWorkbook());style.setFillForegroundColor(backgroudColrList.get(i++));// 设置背景色style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);for (int[] rowCell : indexList) {excelRow = sheet.getRow(rowCell[0]);cell = excelRow.getCell(rowCell[1]);cell.setCellStyle(style);}}}/*** 获取表头样式* @param wb* @return*/public static HSSFCellStyle getTitleCellStyle(HSSFWorkbook wb) {HSSFCellStyle style = wb.createCellStyle();//设置背景色://style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置背景色style.setFillForegroundColor(HSSFColor.WHITE.index);//表头设置为白色背景style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);style.setAlignment(HSSFCellStyle.ALIGN_CENTER);style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.BLACK.index);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLACK.index);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setTopBorderColor(HSSFColor.BLACK.index);//四、设置字体:HSSFFont font = wb.createFont();font.setFontName("宋体");font.setFontHeightInPoints((short) 11);//设置字体大小style.setFont(font);//选择需要用到的字体格式style.setWrapText(true);//设置自动换行return style;}/*** 获取表头样式(有边框)* @param wb* @param configStr 宋体(字体样式),11(字体大小),right(对齐方式),20(行高),B(粗体)#I(斜体)#U(下划线),0顶端对齐(1中心对齐,2下端对齐,3垂直对齐)* @return*/public static HSSFCellStyle getTitleCellStyle(HSSFWorkbook wb, String configStr) {if (configStr == null || "".equals(configStr)) {return getTitleCellStyle(wb);}String[] configArr = configStr.split(",");if (configArr.length < 5) {return getTitleCellStyle(wb);}String fontName = configArr[0];short fontSize = (short) ObjNumberUtils.toInt(configArr[1]);String align = configArr[2];//      short height = (short) ObjNumberUtils.toInt(configArr[3]);String biu = configArr[4];HSSFCellStyle style = wb.createCellStyle();//设置背景色://style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);//表头设置为灰色背景style.setFillForegroundColor(HSSFColor.WHITE.index);//表头设置为白色背景style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//对齐方式if ("left".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_LEFT);} else if ("right".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);} else {style.setAlignment(HSSFCellStyle.ALIGN_CENTER);}style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.BLACK.index);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLACK.index);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setTopBorderColor(HSSFColor.BLACK.index);//四、设置字体:HSSFFont font = wb.createFont();font.setFontName(fontName);font.setFontHeightInPoints(fontSize);//设置字体大小if (biu.indexOf("B") >= 0) {font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);}if (biu.indexOf("N") >= 0) {font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);}if (biu.indexOf("I") >= 0) {font.setItalic(true);}if (biu.indexOf("U") >= 0) {font.setUnderline(FontFormatting.U_SINGLE);}//五、垂直方式if(configArr.length >= 6){Short vertical = Short.valueOf(configArr[5]);style.setVerticalAlignment(vertical);}style.setFont(font);//选择需要用到的字体格式style.setWrapText(true);//设置自动换行return style;}/*** 获取表头样式(有边框)* <p>Description: </p>* @author chenxy* @date 2017-6-22 下午6:18:21* @param wb* @param configStr* @return*/public static HSSFCellStyle getTitleCellStyle2(HSSFWorkbook wb, String configStr) {if (configStr == null || "".equals(configStr)) {return getTitleCellStyle(wb);}String[] configArr = configStr.split(",");if (configArr.length < 5) {return getTitleCellStyle(wb);}String fontName = configArr[0];short fontSize = (short) ObjNumberUtils.toInt(configArr[1]);String align = configArr[2];//short height = (short) ObjNumberUtils.toInt(configArr[3]);String biu = configArr[4];HSSFCellStyle style = wb.createCellStyle();//设置背景色://style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);//表头设置为灰色背景style.setFillForegroundColor(HSSFColor.WHITE.index);//表头设置为白色背景style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//对齐方式if ("left".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_LEFT);} else if ("right".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);} else {style.setAlignment(HSSFCellStyle.ALIGN_CENTER);}//style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);//style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.BLACK.index);//style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLACK.index);//style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setTopBorderColor(HSSFColor.BLACK.index);//四、设置字体:HSSFFont font = wb.createFont();font.setFontName(fontName);font.setFontHeightInPoints(fontSize);//设置字体大小if (biu.indexOf("B") >= 0) {font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);}if (biu.indexOf("N") >= 0) {font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);}if (biu.indexOf("I") >= 0) {font.setItalic(true);}if (biu.indexOf("U") >= 0) {font.setUnderline(FontFormatting.U_SINGLE);}//五、垂直方式if(configArr.length >= 6){Short vertical = Short.valueOf(configArr[5]);style.setVerticalAlignment(vertical);}style.setFont(font);//选择需要用到的字体格式style.setWrapText(true);//设置自动换行return style;}private static String getConfigStr(String configStr, int index) {if (configStr == null || "".equals(configStr)) {return null;}String[] configArr = configStr.split(",");if (configArr.length < index+1) {return null;}return configArr[index];}/*** 获取表格样式* @param wb* @return*/public static HSSFCellStyle getCellStyle(HSSFWorkbook wb) {HSSFCellStyle style = wb.createCellStyle();style.setAlignment(HSSFCellStyle.ALIGN_CENTER);style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.BLACK.index);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLACK.index);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setTopBorderColor(HSSFColor.BLACK.index);//四、设置字体:HSSFFont font = wb.createFont();font.setFontName("宋体");font.setFontHeightInPoints((short) 11);//设置字体大小style.setFont(font);//选择需要用到的字体格式style.setWrapText(true);//设置自动换行//设置文本样式//      DataFormat  format = wb.createDataFormat();//      style.setDataFormat(format.getFormat("General"));return style;}/*** 获取表格样式* @param wb* @param fontName* @param fontSize* @param align* @return*/public static HSSFCellStyle getCellStyle(HSSFWorkbook wb, String fontName, Integer fontSize, String align) {HSSFCellStyle style = wb.createCellStyle();if ("left".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_LEFT);} else if ("right".equals(align)) {style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);} else {style.setAlignment(HSSFCellStyle.ALIGN_CENTER);}style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBottomBorderColor(HSSFColor.BLACK.index);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setLeftBorderColor(HSSFColor.BLACK.index);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setRightBorderColor(HSSFColor.BLACK.index);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setTopBorderColor(HSSFColor.BLACK.index);//四、设置字体:HSSFFont font = wb.createFont();if (fontName == null || "".equals(fontName)) {font.setFontName(fontName);} else {font.setFontName("宋体");}if (fontSize == null || fontSize.intValue() < 0) {font.setFontHeightInPoints((short) 11);} else {font.setFontHeightInPoints((short) fontSize.intValue());}style.setFont(font);//选择需要用到的字体格式style.setWrapText(true);//设置自动换行return style;}
}
public HashMap<String, Object> getExcelStyle() {HashMap<String, Object> configMap = new HashMap<String, Object>();Double mainTitlefontSize = 16.0;Double subTitle1FontSize = 14.0;Double subTitle2FontSize = 14.0;Double subTitle3FontSize = 12.0;Double dataFontSize = 11.0;StringBuffer buf = new StringBuffer();//表头buf = new StringBuffer();buf.append(10).append(",").append(10);buf.append(",center,").append(25).append(",B");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("TitleStyle", buf.toString());//数据体buf = new StringBuffer();buf.append(dataFontSize).append(",").append(dataFontSize);buf.append(",center,").append(25).append(",N");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("DataStyle", buf.toString());//主标题buf = new StringBuffer();buf.append(mainTitlefontSize).append(",").append(mainTitlefontSize).append(",");buf.append("center").append(",").append(36).append(",B");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("MainTitle1Style", buf.toString());//副标题1buf = new StringBuffer();buf.append(subTitle1FontSize).append(",").append(subTitle1FontSize).append(",");buf.append("right").append(",").append(36).append(",B");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("MainTitle2Style", buf.toString());//副标题2buf = new StringBuffer();buf.append(subTitle2FontSize).append(",").append(subTitle2FontSize).append(",");buf.append("right").append(",").append(36).append(",B");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("MainTitle3Style", buf.toString());//副标题3buf = new StringBuffer();buf.append(subTitle3FontSize).append(",").append(subTitle3FontSize).append(",");buf.append("right").append(",").append(36).append(",B");buf.append(",").append(XSSFCellStyle.VERTICAL_CENTER);configMap.put("FootTitleStyle", buf.toString());return configMap;}

多表头支持合并行和列,有标题(可有可无)

String[] columnTitle1 = {"序号", "编号", "姓名", "性别", "年龄", "身高体重指数", "#cspan", "#cspan"};
String[] columnTitle2 = {"#rspan", "#rspan", "#rspan", "#rspan", "#rspan", "身高(cm)", "体重(kg)", "BMI"};
List<String[]> columnTitles = new ArrayList<String[]>();
columnTitles.add(columnTitle1);
columnTitles.add(columnTitle2);
Map<String, Object> configMap = this.getExcelStyle();
configMap.put("DataWidth", "1200");
List<String> mainTitleList = new ArrayList<String>();
mainTitleList.add("xx公司人员结果统计");
mainTitleList.add("2018年8月");
String footTitle = "制作:xx"
File file = ExcelUtils.mulitHeaderCreate("结果统计", mainTitleList, footTitle, columnTitles, dataList, configMap);


单表头,不支持合并行和列

List<String[]> dataList = resultInfo.getObjList();
List<String[]> columnTitleList = new ArrayList<String[]>();
String[] columnTitle = {"序号", "编号", "姓名", "性别", "年龄"};
columnTitleList.add(columnTitle );
String[] sheetNames = {"统计数据"};
List<Collection> dataLists= new ArrayList<Collection>();
dataLists.add(dataList);
File file = ExcelUtils.anySheetsCreate("XX公司计数据", sheetNames, columnTitleList, dataLists);

excel工具类ExcelUtils相关推荐

  1. 读取Excel工具类ExcelUtils

    依赖包 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency><group ...

  2. Excel工具类--下载

    1.使用Excel工具类ExcelUtils,导包 2.前端代码,一个普通a标签 3.后端代码 ToolUtil.getExcelTitle 是额外提供的工具类,来处理不同浏览器下的乱码问题 Exce ...

  3. 操作Excel工具类:ExcelUtils.java

    项目中,时常会需要导入导出Excel的需求,因此我专门花时间设计了工具类. 所需依赖 <!-- 处理xls或xlsx格式的Excel表格导入导出的依赖 --><dependency& ...

  4. Java解析Excel工具类(兼容xls和xlsx)

    依赖jar <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml< ...

  5. java 兼容excel_Java解析Excel工具类(兼容xls和xlsx)

    依赖jar org.apache.poi poi-ooxml 4.0.1 ExcelUtils.java package javax.utils; import java.io.File; impor ...

  6. 导出excel工具类

    1.excel工具类代码如下 package com.spring.excel.utils; import org.apache.poi.hssf.usermodel.*; import org.ap ...

  7. java获取excle表格对象_Java使用excel工具类导出对象功能示例

    本文实例讲述了Java使用excel工具类导出对象功能.分享给大家供大家参考,具体如下: package com.gcloud.common; import org.apache.poi.ss.use ...

  8. Java导入导出Excel工具类ExcelUtil

    前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hiberna ...

  9. Python Excel工具类封装, 实现excel表头加颜色

    封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...

  10. 自定义POI的excel工具类-xls-xlsx

    自定义POI的excel工具类-xls-xlsx 使用jdk8(java8)实现Excel导出,随意切换 xls和xlsx.自己只是封装了比较常用方法,07版生成还有bug.ε=(´ο`*)))唉 j ...

最新文章

  1. linux 下camera调试笔记【转】
  2. webpack打包处理js文件中的高级语法
  3. iphone清理缓存小技巧_那些不为人知的iPhone隐藏小技巧
  4. CopyFile and Directory By channel
  5. 对比学习simSiam(一)--Exploring Simple Siamese Representation Learning总体理解
  6. 网站防刷方案 -摘自网络
  7. 爬虫模拟登陆手机验证码_爬虫入门到精通-headers的详细讲解(模拟登录知乎)...
  8. 开源SUP对接API卡盟程序卡信乐v2.0源码
  9. Java多线程之后台线程不执行finally
  10. 窄脉冲matlab实现,[求助]如何获得与50Hz工频同步的窄脉冲信号
  11. python爬取京东数据加载失败_Python爬取京东商品数据
  12. win10 输入法工具无法设置水平
  13. PS常用快捷键大全(2020版)
  14. 3.5.1_2 Maven - pom.xml 添加maven-assembly-plugin(官方标准打包插件)
  15. 高中计算机学业水平测试知识点总结,高中生物学业水平测试知识点总结
  16. “地表最贵iPhone”到货,iPhone XS 系列手机等你来测!
  17. java h265_2019-04-19 使用FFMPEG 解码HEVC(H265)
  18. 安装pytorch报错torch.cuda.is_available()=false的解决方法
  19. iptables拦截域名_使用iptables封锁对某个域名的DNS查询
  20. python编程设计高级_Python编程高级技巧| 选择好的名称

热门文章

  1. java飞机票打折问题
  2. SDC设计约束(4)——其他SDC命令
  3. 基于AdaBoostSVM的不平衡数据训练(原理+代码,超详细)
  4. 分享经过头条多个部门共十轮面试的感受给大家!
  5. 数据集对逆合成领域有多重要!
  6. IO[File_API学习]
  7. 属于python保留字的是_属鼠的男人全集:属鼠男的性格、命运、属相婚配表等-第一星座网...
  8. Flink任务资源设置
  9. 使用Scala首先运行加特林负载测试
  10. 一颗芯片的前世今生(5)——封装测试