excel自定义表格poi导出
生活随笔
收集整理的這篇文章主要介紹了
excel自定义表格poi导出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.引入poi架包
<!-- POI --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.16</version></dependency>2.添加excel工具類
package com.yss.datamiddle.utils;import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; import org.aspectj.weaver.ast.Test; import org.springframework.core.io.ClassPathResource;import java.io.*; import java.util.*; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;/*** 使用一個已經存在的Excel作為模板,可以對當前的模板Excel進行修改操作,* 然后重新輸出為流,或者存入文件系統當中。*** @Description: excel模板操作** */ public class ExcelTemplate {private String path;private Workbook workbook;private Sheet[] sheets;private Sheet sheet;private Throwable ex;private List<Cell> cellList = null;private Pattern doublePattern = Pattern.compile("^[0-9]+[.]{0,1}[0-9]*[dD]{0,1}$");/*** 通過模板Excel的路徑初始化* */public ExcelTemplate(String path) {this.path = path;init();}public ExcelTemplate(InputStream is) {init(is);}private void init(){ClassPathResource classPathResource = new ClassPathResource(path);// File file = new File(path); // if (file.exists() && (path == null // || (!path.endsWith(".xlsx") && !path.endsWith(".xls")))) { // ex = new IOException("錯誤的文件格式"); // } else{try (InputStream is = classPathResource.getInputStream()){workbook = WorkbookFactory.create(is);sheets = new Sheet[workbook.getNumberOfSheets()];for(int i = 0;i < sheets.length;i++){sheets[i] = workbook.getSheetAt(i);}if(sheets.length > 0) {sheet = sheets[0];}sheet.setForceFormulaRecalculation(true);} catch (EncryptedDocumentException e) {ex = e;} catch (IOException | InvalidFormatException e) {ex = e;} // }}private void init(InputStream is){try {workbook = WorkbookFactory.create(is);sheets = new Sheet[workbook.getNumberOfSheets()];for(int i = 0;i < sheets.length;i++){sheets[i] = workbook.getSheetAt(i);}if(sheets.length > 0) {sheet = sheets[0];}sheet.setForceFormulaRecalculation(true);} catch (EncryptedDocumentException e) {ex = e;} catch (IOException | InvalidFormatException e) {ex = e;}}private boolean initSheet(int sheetNo){if(!examine() || sheetNo < 0 || sheetNo > workbook.getNumberOfSheets() - 1) {return false;}int sheetNum = workbook.getNumberOfSheets();sheets = new Sheet[sheetNum];for(int i = 0;i < sheetNum;i++){if(i == sheetNo) {sheet = workbook.getSheetAt(i);}sheets[i] = workbook.getSheetAt(i);}sheet = workbook.getSheetAt(sheetNo);sheet.setForceFormulaRecalculation(true);return true;}/*** 驗證模板是否可用* @return true-可用 false-不可用* */public boolean examine(){if(ex == null && workbook != null) {return true;}return false;}private boolean examineSheetRow(int index){if(index < 0 || index > sheet.getLastRowNum()) {return false;}return true;}/*** 使用一個已經存在的row作為模板,* 從sheet[sheetNo]的toRowNum行開始插入這個row模板的副本** @param sheetNo 需要操作的Sheet的編號* @param fromRowStartIndex 模板row區域的開始索引* @param fromRowEndIndex 模板row區域的結束索引* @param toRowIndex 開始插入的row索引值* @param copyNum 復制的數量* @param delRowTemp 是否刪除模板row區域* @return int 插入的行數量* @throws IOException* */public int addRowByExist(int sheetNo,int fromRowStartIndex, int fromRowEndIndex,int toRowIndex, int copyNum,boolean delRowTemp)throws IOException {LinkedHashMap<Integer, LinkedList<String>> map = new LinkedHashMap<>();for(int i = 1;i <= copyNum;i++){map.put(i,new LinkedList<>());}return addRowByExist(sheetNo,fromRowStartIndex,fromRowEndIndex,toRowIndex,map,delRowTemp);}/*** 使用一個已經存在的row作為模板,* 從sheet[sheetNo]的toRowNum行開始插入這個row模板的副本,* 并且使用areaValue從左至右,從上至下的替換掉* row區域中值為 ${} 的單元格的值** @param sheetNo 需要操作的Sheet的編號* @param fromRowIndex 模板行的索引* @param toRowIndex 開始插入的row索引* @param areaValues 替換模板row區域的${}值* @return int 插入的行數量* @throws IOException* */public int addRowByExist(int sheetNo,int fromRowIndex, int toRowIndex,LinkedHashMap<Integer,LinkedList<String>> areaValues)throws IOException {return addRowByExist(sheetNo,fromRowIndex,fromRowIndex,toRowIndex,areaValues,true);}/*** 使用一個已經存在的行區域作為模板,* 從sheet的toRowNum行開始插入這段行區域,* areaValue會從左至右,從上至下的替換掉row區域* 中值為 ${} 的單元格的值** @param sheetNo 需要操作的Sheet的編號* @param fromRowStartIndex 模板row區域的開始索引* @param fromRowEndIndex 模板row區域的結束索引* @param toRowIndex 開始插入的row索引* @param areaValues 替換模板row區域的${}值* @param delRowTemp 是否刪除模板row區域* @return int 插入的行數量* @throws IOException* */public int addRowByExist(int sheetNo,int fromRowStartIndex, int fromRowEndIndex,int toRowIndex,LinkedHashMap<Integer,LinkedList<String>> areaValues, boolean delRowTemp)throws IOException {exception();if(!examine()|| !initSheet(sheetNo)|| !examineSheetRow(fromRowStartIndex)|| !examineSheetRow(fromRowEndIndex)|| fromRowStartIndex > fromRowEndIndex) {return 0;}int areaNum;List<Row> rows = new ArrayList<>();if(areaValues != null){int n = 0,f = areaValues.size() * (areaNum = (fromRowEndIndex - fromRowStartIndex + 1));// 在插入前騰出空間,避免新插入的行覆蓋原有的行shiftAndCreateRows(sheetNo,toRowIndex,f);// 讀取需要插入的數據for (Integer key:areaValues.keySet()){List<Row> temp = new LinkedList<>();// 插入行for(int i = 0;i < areaNum;i++){int num = areaNum * n + i;Row toRow = sheet.getRow(toRowIndex + num);Row row;if(toRowIndex >= fromRowEndIndex) {row = copyRow(sheetNo,sheet.getRow(fromRowStartIndex + i),sheetNo,toRow,true,true);} else {row = copyRow(sheetNo,sheet.getRow(fromRowStartIndex + i + f),sheetNo,toRow,true,true);}temp.add(row);}// 使用傳入的值覆蓋${}或者N${}replaceMark(temp,areaValues.get(key));rows.addAll(temp);n++;}if(delRowTemp){if(toRowIndex >= fromRowEndIndex) {removeRowArea(sheetNo,fromRowStartIndex,fromRowEndIndex);} else {removeRowArea(sheetNo,fromRowStartIndex + f,fromRowEndIndex + f);}}}return rows.size();}/*** 使用一個已經存在的列區域作為模板,* 從sheet的toColumnIndex列開始插入這段列區域,* areaValue會從上至下,從左至右的替換掉列區域* 中值為 ${} 的單元格的值** @param sheetNo 需要操作的Sheet的編號* @param fromColumnStartIndex 模板列區域的開始索引* @param fromColumnEndIndex 模板列區域的結束索引* @param toColumnIndex 開始插入的列索引* @param areaValues 替換模板列區域的${}值* @param delColumnTemp 是否刪除模板列區域* @return int 插入的列數量* @throws IOException* */public int addColumnByExist(int sheetNo,int fromColumnStartIndex, int fromColumnEndIndex,int toColumnIndex,LinkedHashMap<Integer,LinkedList<String>> areaValues, boolean delColumnTemp)throws IOException{exception();if(!examine()|| !initSheet(sheetNo)|| fromColumnStartIndex > fromColumnEndIndex|| toColumnIndex < 0) {return 0;}// 合并區域的列的數量int areaNum;List<Integer> n = new ArrayList<>();n.add(0);if(areaValues != null){int f = areaValues.size() * (areaNum = (fromColumnEndIndex - fromColumnStartIndex + 1));// 創建空白的列shiftAndCreateColumns(sheetNo,toColumnIndex-1,f);// 獲取所有合并區域List<CellRangeAddress> crds = sheet.getMergedRegions();// 讀取需要插入的數據for (Integer key:areaValues.keySet()){for(int i = 0;i < areaNum;i++){// 獲取插入的位置int position = toColumnIndex + n.get(0) * areaNum + i;// 插入的列的位置是在復制區域之后if(toColumnIndex >= fromColumnStartIndex) {copyColumn(sheetNo,fromColumnStartIndex + i,sheetNo,position,true);}// 插入的列的位置是在復制區域之前else {copyColumn(sheetNo,fromColumnStartIndex + i + f,sheetNo,position,true);}}// 復制源列的合并區域到新添加的列if(crds != null){crds.forEach(crd -> {// 列偏移量int offset = toColumnIndex - fromColumnStartIndex + areaNum * n.get(0);// 合并區域的寬度int rangeAreaNum = crd.getLastColumn() - crd.getFirstColumn() + 1;// 原合并區域的首列int firstColumn = crd.getFirstColumn();// 需要添加的合并區域首列int addFirstColumn = firstColumn + offset;// 根據插入的列的位置是在復制區域之前還是之后// firstColumn和addFirstColumn分配不同的值firstColumn = toColumnIndex >= fromColumnStartIndex ? firstColumn : firstColumn - f;addFirstColumn = toColumnIndex >= fromColumnStartIndex ? addFirstColumn : toColumnIndex + areaNum * n.get(0);if(firstColumn >= fromColumnStartIndex && firstColumn < fromColumnEndIndex){if ((firstColumn + rangeAreaNum - 1) > fromColumnEndIndex) {rangeAreaNum = fromColumnEndIndex - firstColumn + 1;}if(rangeAreaNum > areaNum){mergedRegion(sheetNo,crd.getFirstRow(),crd.getLastRow(),addFirstColumn,addFirstColumn + areaNum - 1);}else {mergedRegion(sheetNo,crd.getFirstRow(),crd.getLastRow(),addFirstColumn,addFirstColumn + rangeAreaNum - 1);}}});}// 填充${}List<String> fillValues = new ArrayList<>(areaValues.get(key));if (fillValues == null || fillValues.size() == 0){n.replaceAll(i -> i + 1);continue;}List<Cell> needFillCells;initCellList(sheetNo);needFillCells = cellList;// 獲取所有的值為${}單元格needFillCells = needFillCells.stream().filter(c -> {if(c != null && c.getCellTypeEnum() == CellType.STRING){if ("${}".equals(c.getStringCellValue()) || "N${}".equals(c.getStringCellValue())) {return true;}}return false;}).collect(Collectors.toList());if (needFillCells == null){n.replaceAll(i -> i + 1);continue;}// 所有的${}單元格按照列從小到大,行從小到大的順序排序needFillCells.sort((c1,c2) -> {if (c1 == null && c2 == null) {return 0;}if (c1 == null) {return 1;}if (c2 == null) {return -1;}if(c1.getColumnIndex() > c2.getColumnIndex()) {return 1;} else if(c1.getColumnIndex() < c2.getColumnIndex()) {return -1;} else {if(c1.getRowIndex() > c2.getRowIndex()) {return 1;} else if(c1.getRowIndex() < c2.getRowIndex()) {return -1;} else {return 0;}}});needFillCells.stream().filter(c -> {if(c == null) {return false;}// 篩選出當前需要填充的單元格return c.getColumnIndex() >= toColumnIndex + areaNum * n.get(0)&& c.getColumnIndex() <= toColumnIndex + areaNum * (n.get(0) + 1);}).forEach(c -> {if(fillValues.size() > 0){// 設置為列的首行,再移除掉首行的值String value = fillValues.stream().filter(Objects::nonNull).findFirst().orElse("");if (doublePattern.matcher(value == null ? "": value).find()){c.setCellValue(Double.parseDouble(value));}else {c.setCellValue(value);}CellStyle cellStyle = c.getCellStyle();cellStyle.setWrapText(true);c.setCellStyle(cellStyle);fillValues.remove(0);}});n.replaceAll(i -> i + 1);}if(delColumnTemp){if(toColumnIndex >= fromColumnStartIndex) {removeColumnArea(sheetNo,fromColumnStartIndex,fromColumnEndIndex);} else {removeColumnArea(sheetNo,fromColumnStartIndex + f,fromColumnEndIndex + f);}}}return n.get(0);}/*** 使用一個已經存在的列區域作為模板,* 從sheet的toColumnIndex列開始插入這段列區域** @param sheetNo 需要操作的Sheet的編號* @param fromColumnStartIndex 模板列區域的開始索引* @param fromColumnEndIndex 模板列區域的結束索引* @param toColumnIndex 開始插入的列索引* @param copyNum 復制數量* @param delColumnTemp 是否刪除模板列區域* @return int 插入的列數量* @throws IOException* */public int addColumnByExist(int sheetNo,int fromColumnStartIndex, int fromColumnEndIndex,int toColumnIndex,int copyNum, boolean delColumnTemp)throws IOException{LinkedHashMap<Integer, LinkedList<String>> map = new LinkedHashMap<>();for(int i = 1;i <= copyNum;i++){map.put(i,new LinkedList<>());}return addColumnByExist(sheetNo,fromColumnStartIndex,fromColumnEndIndex,toColumnIndex,map,delColumnTemp);}/*** 填充Excel當中的變量** @param fillValues 填充的值* @return int 受影響的變量數量* @throws IOException**/public int fillVariable(Map<String,String> fillValues) throws IOException {return fillVariable(0,fillValues);}/*** 填充Excel當中的變量** @param sheetNo 需要操作的Sheet的編號* @param fillValues 填充的值* @return int 受影響的變量數量* @throws IOException**/public int fillVariable(int sheetNo,Map<String,String> fillValues)throws IOException {exception();if(!examine()|| sheetNo < 0|| sheetNo > sheets.length - 1|| fillValues == null|| fillValues.size() == 0) {return 0;}// 驗證${}格式Pattern pattern = Pattern.compile("(\\$\\{[^\\}]+})");// 把所有的${}按Cell分類,也就是說如果一個Cell中存在兩個${},// 這兩個變量的Cell應該一樣Map<Cell,Map<String,String>> cellVal = new HashMap<>();List<Integer> ns = new ArrayList<>();ns.add(0);fillValues.forEach((k,v) ->{// 找到變量所在的單元格Cell cell = findCells(sheetNo,s -> {if(s == null || "".equals(s)) {return false;}Matcher matcher = pattern.matcher(s);while(matcher.find()){String variable = matcher.group(1);if(variable != null&& formatParamCode(variable).equals(k.trim())) {return true;}}return false;}).stream().findFirst().orElse(null);if(cell != null){Map<String,String> cellValMap = cellVal.get(cell);if(cellValMap == null) {cellValMap = new HashMap<>();}cellValMap.put(k,v);cellVal.put(cell,cellValMap);ns.replaceAll(n -> n + 1);}});cellVal.forEach((k,v) -> {String cellValue = k.getStringCellValue();String value = composeMessage(cellValue,v);Matcher matcher = doublePattern.matcher(value == null ? "": value);if (matcher.find()){k.setCellValue(Double.parseDouble(value));}else {k.setCellValue(value);}CellStyle cellStyle = k.getCellStyle();cellStyle.setWrapText(true);k.setCellStyle(cellStyle);});return ns.get(0);}/*** 指定cell插入圖片** @param sheetNo 需要操作的Sheet的編號* @param imageBytes 圖片字節流* @param imgType 圖片類型(舉例:png 傳入 Workbook.PICTURE_TYPE_PNG作為參數)* @param startRow 開始行* @param endRow 結束行* @param startCol 開始列* @param endCol 結束列* */public void insertPicture(int sheetNo,byte[] imageBytes,int imgType,int startRow,int endRow,int startCol,int endCol) throws IOException {exception();if (!initSheet(sheetNo)) {return;}Drawing patriarch = sheet.createDrawingPatriarch();ClientAnchor anchor = null;if (sheet instanceof XSSFSheet) {anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) startCol, startRow, (short) endCol, endRow);} else {anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) startCol, startRow, (short) endCol, endRow);}anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);patriarch.createPicture(anchor, workbook.addPicture(imageBytes, imgType));if (sheet instanceof XSSFSheet) {List<XSSFShape> shapes = ((XSSFDrawing)patriarch).getShapes();for (XSSFShape shape : shapes) {XSSFPicture picture = (XSSFPicture) shape;picture.getPreferredSize();}}else {List<HSSFShape> list = ((HSSFSheet)sheet).getDrawingPatriarch().getChildren();for (HSSFShape shape : list) {if (shape instanceof HSSFPicture) {HSSFPicture picture = (HSSFPicture) shape;picture.getClientAnchor();picture.getPictureData();}}}}/*** 根據行坐標和列坐標定位到單元格,填充單元格** @param sheetNo 需要操作的Sheet的編號* @param rowIndex 行坐標* @param columnIndex 列坐標* @param value 填充的值* @return boolean 是否成功* @throws IOException**/public boolean fillByCoordinate(int sheetNo,int rowIndex,int columnIndex,String value)throws IOException {exception();if(!initSheet(sheetNo)) {return false;}Row row = sheet.getRow(rowIndex);if(row == null) {return false;}Cell cell = row.getCell(columnIndex);if(cell == null) {return false;}if (doublePattern.matcher(value == null ? "": value).find()){cell.setCellValue(Double.parseDouble(value));}else{cell.setCellValue(value);}return true;}/*** 根據斷言predicate查找sheet當中符合條件的cell** @param sheetNo 需要操作的Sheet的編號* @param predicate 篩選的斷言* @return List<Cell> 符合條件的Cell* */public List<Cell> findCells(int sheetNo,Predicate<String> predicate){Objects.requireNonNull(predicate);initCellList(sheetNo);return cellList.stream().map(c -> {if(c != null && c.getCellTypeEnum() == CellType.STRING) {return c.getStringCellValue();}return null;})// Cell流轉換為String流.filter(predicate).map(s -> cellList.stream().filter(c -> {if(c != null && c.getCellTypeEnum() == CellType.STRING&& s.equals(c.getStringCellValue())) {return true;}return false;}).findFirst().orElse(null))// String流重新轉換位Cell流.filter(c -> c != null).collect(Collectors.toList());}/*** 根據斷言predicate查找sheet當中符合條件的Row** @param sheetNo 需要操作的Sheet的編號* @param predicate 篩選的斷言* @return List<Row> 符合條件的Row* */public List<Row> findRows(int sheetNo,Predicate<Row> predicate){if(!examine() || !initSheet(sheetNo)) {return null;}List<Row> rows = new ArrayList<>();for(int i = sheet.getFirstRowNum();i <= sheet.getLastRowNum();i++){Row row = sheet.getRow(i);if(predicate.test(row)) {rows.add(row);}}return rows;}/*** 提取變量中的值,比如 formatParamCode("${1234}"),* 會得到結果1234** @param paramCode 需要提取的字符串* @return String* */private String formatParamCode(String paramCode){if(paramCode == null) {return "";}return paramCode.replaceAll("\\$", "").replaceAll("\\{", "").replaceAll("\\}", "");}/*** 使用paramData當中的值替換data當中的變量** @param data 需要提取的字符串* @param paramData 需要替換的值* @return String* */private String composeMessage(String data, Map<String,String> paramData){String regex = "\\$\\{(.+?)\\}";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(data == null ? "": data);StringBuffer msg = new StringBuffer();while (matcher.find()) {String key = matcher.group(1);// 鍵名String value = paramData.get(key);// 鍵值if(value == null) {value = "";} else {value = value.replaceAll("\\$", "\\\\\\$");}matcher.appendReplacement(msg, value);}matcher.appendTail(msg);return msg.toString();}/*** 計算excel公式中的單元格的列和行加上數值后的結果** @param isColumn 是否是行的計算* @param value 原始值* @param addNum 添加的數量* @return String* */private String addRowOrColumnIndex(boolean isColumn,String value,int addNum){value = value == null ? "" : value;if(isColumn){if (!Pattern.compile("^[A-Z]+$").matcher(value).find()) {return value;}char[] cs = value.toCharArray();int cardinal = 0;// 組合轉換為數字for (int i = cs.length - 1; i >= 0; i--) {cardinal += Math.pow(26,cs.length - 1 - i) * (cs[i] - 64);}// 加上添加后的數值cardinal += addNum;// 不能為0cardinal = cardinal <= 0 ? 1 : cardinal;// 是否需要向前借一位boolean borrowBit = false;Stack<Character> stack = new Stack<>();// 數字轉換為組合while (true && cardinal > 0){int mode = cardinal % 26;// 如果到達了第一位if(cardinal >= 1 && cardinal < 26){// 是否需要借位if (borrowBit) {mode -= 1;}// 首位借位之后必須大于0才能添加if (mode > 0) {stack.add((char)(mode + 64));}break;}cardinal -= mode;cardinal /= 26;if (borrowBit){if (mode != 0) {mode -= 1;}// 如果借位的時候,發現本身也為0,需要向前再借位else{mode = 25;borrowBit = true;stack.add((char)(mode + 64));continue;}}if (mode == 0){mode = 26;borrowBit = true;}else {borrowBit = false;}stack.add((char)(mode + 64));}int size = stack.size();char[] chars = new char[size];for (int j = size - 1; j >= 0; j--) {chars[size - 1 - j] = stack.get(j);}return new String(chars);}else {if(!Pattern.compile("^[0-9]+$").matcher(value).find()) {return value;}try{int intValue = Integer.parseInt(value);intValue += addNum;if (intValue <= 0) {return "1";}return Integer.toString(intValue);}catch (NumberFormatException e){return value;}}}/*** 修改公式里面單元格參數的坐標** @param formula 公式* @param index 第幾個單元格參數* @param rowAddNum 給行添加的數量* @param columnAddNum 給列添加的數量* @return String* */private String composeFormula(String formula,int index,int rowAddNum,int columnAddNum){String regex = "[A-Z]+[0-9]+";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(formula == null ? "" : formula);List<String> valueList = new LinkedList<>();String oldFormula = formula;while(matcher.find()){String value = matcher.group();valueList.add(value);formula = formula.replaceFirst(value,"@&");}if (index >= 0 && index < valueList.size()){String value = valueList.get(index);Matcher columnMatcher = Pattern.compile("[A-Z]+").matcher(value);String newValue = value;if (columnMatcher.find()){String columnIndex = columnMatcher.group();String rowIndex = value.replaceAll(columnIndex,"");columnIndex = addRowOrColumnIndex(true,columnIndex,columnAddNum);rowIndex = addRowOrColumnIndex(false,rowIndex,rowAddNum);newValue = columnIndex + rowIndex;}valueList.set(index,newValue);}String[] spilts = formula.split("@&");if (spilts.length == 0){if (valueList.size() == 1) {return valueList.get(0);}return oldFormula;}StringBuffer newFormula = new StringBuffer();int position = 0;for (int i = 0; i < spilts.length; i++) {newFormula.append(spilts[i]);if (position < valueList.size()){newFormula.append(valueList.get(position++));}}return newFormula.toString();}/*** 獲取單元格里面公式的變量數量* 例如公式 SUM(AP40:AV40),含有兩個單元格變量 AP40和AV40,* 使用此方法會返回2** @param cell 需要操作的單元格* @return int 單元格變量的數量* */public int getFormulaVariableNum(Cell cell){if (cell == null || cell.getCellTypeEnum() != CellType.FORMULA) {return 0;}String formula = cell.getCellFormula();Matcher matcher = Pattern.compile("[A-Z]+[0-9]+").matcher(formula == null ? "" : formula);int count = 0;while(matcher.find()){count++;}return count;}/*** 修改單元格的公式的參數* excel的所有列按照如下規則分布,* A,B,C,D...Z,AA,AB...AZ,BA,BB...BZ...以此類推,* 你可以看成是一個關于A,B,C...Z的排列組合問題** 舉例:* 單元格cell的公式為 SUM(AP40:AV40) 是求單元格 AP40 到 AV40的單元格的和,* 其中AP40中的AP表示單元格的列坐標,40表示橫坐標,AV40類推。* 如果使用方法 composeCellFormula(cell,0,2,5),則cell的公式會修改為 SUM(AU42:AV40)** @param cell 需要修改的單元格* @param index 第幾個單元格參數* @param rowAddNum 給行添加的數量* @param columnAddNum 給列添加的數量* @return String* */public void composeCellFormula(Cell cell,int index,int rowAddNum,int columnAddNum){if (cell == null || cell.getCellTypeEnum() != CellType.FORMULA) {return;}if (cell instanceof HSSFCell) {throw new IllegalArgumentException("4.1.1及之前的版本的POI的處理xls文件的公式單元格有bug,建議換成xlsx文件," +"或者去官網查看哪個版本修復了這個bug(https://bz.apache.org/bugzilla/show_bug.cgi?id=64517),換成此版本POI。" +"如果引用的POI版本已經是修復了此BUG的版本的POI,可以刪掉這個異常提示!");}String formula = cell.getCellFormula();cell.setCellFormula(composeFormula(formula,index,rowAddNum,columnAddNum));}// 初始化cellListprivate void initCellList(int sheetNo){cellList = new ArrayList<>();if(examine() && !initSheet(sheetNo)) {return;}int rn = sheet.getLastRowNum();for(int i = 0;i <= rn;i++){Row row = sheet.getRow(i);if(row != null){short cn = row.getLastCellNum();for (int j = 0;j < cn;j++){cellList.add(row.getCell(j));}}}}/*** 替換掉所有行區域中的所有 ${} 標記* valueList對rows中${}替換的順序是:* 從左至右,從上到下** @param rows 行區域* @param vl 替換的值* */private void replaceMark(List<Row> rows,List<String> vl){if (rows == null || vl == null) {return;}List<String> valueList = new ArrayList<>(vl);rows.forEach(r -> {if(r != null){r.forEach(c -> {if (c != null){if (c.getCellTypeEnum() == CellType.STRING){if("${}".equals(Optional.ofNullable(c.getStringCellValue()).orElse("").trim())){if(valueList == null) {return;}String value = valueList.stream().filter(Objects::nonNull).findFirst().orElse(null);c.setCellValue(value);CellStyle cellStyle = c.getCellStyle();cellStyle.setWrapText(true);c.setCellStyle(cellStyle);if(value != null) {valueList.remove(valueList.indexOf(value));}}else if("N${}".equals(Optional.ofNullable(c.getStringCellValue()).orElse("").trim())){if(valueList == null) {return;}String value = valueList.stream().filter(Objects::nonNull).findFirst().orElse(null);Matcher matcher = doublePattern.matcher(value == null ? "" : value);if (matcher.find()){c.setCellValue(Double.parseDouble(value));CellStyle cellStyle = c.getCellStyle();cellStyle.setWrapText(true);c.setCellStyle(cellStyle);if(value != null) {valueList.remove(valueList.indexOf(value));}}else {throw new IllegalArgumentException("N${} 所替換的內容只能為數字,非法參數\"" + value + "\"");}}}}});}});}/*** 復制Row到sheet中的另一個Row** @param fromSheetNo 復制的行所在的sheet* @param fromRow 需要復制的行* @param toSheetNo 粘貼的行所在的sheet* @param toRow 粘貼的行* @param copyValueFlag 是否需要復制值* @param needMerged 是否需要合并單元格*/private Row copyRow(int fromSheetNo,Row fromRow, int toSheetNo,Row toRow, boolean copyValueFlag,boolean needMerged) {if(fromSheetNo < 0 || fromSheetNo > workbook.getNumberOfSheets()|| toSheetNo < 0 || toSheetNo > workbook.getNumberOfSheets()) {return null;}if (fromRow == null) {return null;}if(toRow == null){Sheet sheet = workbook.getSheetAt(toSheetNo);if(sheet == null) {return null;}toRow = sheet.createRow(fromRow.getRowNum());if(toRow == null) {return null;}}// 設置高度toRow.setHeight(fromRow.getHeight());// 遍歷行中的單元格for(Cell c:fromRow){Cell newCell = toRow.createCell(c.getColumnIndex());copyCell(c, newCell, copyValueFlag);}// 如果需要合并if(needMerged){Sheet fromSheet = workbook.getSheetAt(fromSheetNo);Sheet toSheet = workbook.getSheetAt(toSheetNo);// 遍歷行當中的所有的合并區域List<CellRangeAddress> crds = fromSheet.getMergedRegions();if(crds != null && crds.size() > 0){for(CellRangeAddress crd : crds){// 如果當前合并區域的首行為復制的源行if(crd.getFirstRow() == fromRow.getRowNum()) {// 創建對應的合并區域CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(),(toRow.getRowNum() + (crd.getLastRow() - crd.getFirstRow())),crd.getFirstColumn(),crd.getLastColumn());// 添加合并區域safeMergedRegion(toSheetNo,newCellRangeAddress);}}}}return toRow;}/*** 復制sheet中列的另一列** @param fromSheetNo 復制的行所在的sheet* @param fromColumnIndex 需要復制的行索引* @param toSheetNo 粘貼的行所在的sheet* @param toColumnIndex 粘貼的行* @param copyValueFlag 是否需要復制值*/private void copyColumn(int fromSheetNo,int fromColumnIndex,int toSheetNo,int toColumnIndex,boolean copyValueFlag) {if(fromSheetNo < 0 || fromSheetNo > workbook.getNumberOfSheets()|| toSheetNo < 0 || toSheetNo > workbook.getNumberOfSheets()) {return;}Sheet fromSheet = workbook.getSheetAt(fromSheetNo);Sheet toSheet = workbook.getSheetAt(toSheetNo);for(int i = 0;i <= fromSheet.getLastRowNum();i++){Row fromRow = fromSheet.getRow(i);Row toRow = toSheet.getRow(i);if(fromRow == null) {continue;}if(toRow == null) {toRow = toSheet.createRow(i);}if(toRow == null) {continue;}// 設置高度toRow.setHeight(fromRow.getHeight());Cell srcCell = fromRow.getCell(fromColumnIndex);Cell distCell = toRow.getCell(toColumnIndex);if(srcCell == null) {continue;}if(distCell == null) {distCell = toRow.createCell(toColumnIndex);}// 設置列寬toSheet.setColumnWidth(toColumnIndex,fromSheet.getColumnWidth(fromColumnIndex));copyCell(srcCell,distCell,copyValueFlag);}}/*** 復制Cell到sheet中的另一個Cell** @param srcCell 需要復制的單元格* @param distCell 粘貼的單元格* @param copyValueFlag true則連同cell的內容一起復制*/private void copyCell(Cell srcCell, Cell distCell, boolean copyValueFlag) {if (srcCell == null || distCell == null) {return;}// 獲取源單元格的樣式CellStyle srcStyle = srcCell.getCellStyle();// 復制樣式distCell.setCellStyle(srcStyle);// 復制評論if(srcCell.getCellComment() != null) {distCell.setCellComment(srcCell.getCellComment());}// 不同數據類型處理CellType srcCellType = srcCell.getCellTypeEnum();if(copyValueFlag) {if(srcCellType == CellType.NUMERIC) {if(DateUtil.isCellDateFormatted(srcCell)) {distCell.setCellValue(srcCell.getDateCellValue());} else {distCell.setCellValue(srcCell.getNumericCellValue());}} else if(srcCellType == CellType.STRING) {distCell.setCellValue(srcCell.getRichStringCellValue());} else if(srcCellType == CellType.BLANK) {} else if(srcCellType == CellType.BOOLEAN) {distCell.setCellValue(srcCell.getBooleanCellValue());} else if(srcCellType == CellType.ERROR) {distCell.setCellErrorValue(srcCell.getErrorCellValue());} else if(srcCellType == CellType.FORMULA) {distCell.setCellFormula(srcCell.getCellFormula());} else {}}}/*** 合并單元格區域,本方法是安全的操作,在出現合并沖突的時候,* 分割合并區域,然后最大限度的合并沖突區域** 使用此方法而不是采用addMergedRegion()和* addMergedRegionUnsafe()合并單元格區間,* 因為此方法會自行解決合并區間沖突,避免報錯或者生成* 無法打開的excel** @param sheetNo 需要操作的Sheet的編號* @param firstRow 開始行* @param lastRow 結束行* @param firstCol 開始列* @param lastCol 結束列* */public void mergedRegion(int sheetNo,int firstRow, int lastRow, int firstCol, int lastCol){if(firstRow > lastRow || firstCol > lastCol) {return;}CellRangeAddress address = new CellRangeAddress(firstRow,lastRow,firstCol,lastCol);safeMergedRegion(sheetNo,address);}/*** 合并單元格區域,本方法是安全的操作,在出現合并沖突的時候,* 分割合并區域,然后最大限度的合并沖突區域** @param sheetNo 需要操作的Sheet的編號* @param rangeAddress 合并的單元格區域* */private void safeMergedRegion(int sheetNo,CellRangeAddress rangeAddress){if(!examine() || !initSheet(sheetNo) || rangeAddress == null) {return;}// 獲取所有合并的區域List<CellRangeAddress> crds = sheet.getMergedRegions();if(crds == null) {return;}// 獲取描述單元格區域的坐標,// 在首行和首列,坐標等于行編號,// 在末行和末列,坐標等于行編號加1int firstRow = rangeAddress.getFirstRow();int lastRow = rangeAddress.getLastRow() + 1;int firstColumn = rangeAddress.getFirstColumn();int lastColumn = rangeAddress.getLastColumn() + 1;// 查找沖突的單元格區域CellRangeAddress conflictRange = crds.stream().filter(crd -> {// 獲取單元格區域的坐標int cFirstRow = crd.getFirstRow();int cLastRow = crd.getLastRow() + 1;int cFirstColumn = crd.getFirstColumn();int cLastColumn = crd.getLastColumn() + 1;// 每個合并單元格區域看成一個長方形// 計算兩個長方形中心的X坐標的距離float xDistance = (float)(lastColumn + firstColumn)/2- (float)(cLastColumn + cFirstColumn)/2;// 每個合并單元格區域看成一個長方形// 計算兩個長方形中心的Y坐標的距離float yDistance = (float)(lastRow + firstRow)/2- (float)(cLastRow + cFirstRow)/2;// 獲取距離的絕對值xDistance = xDistance >= 0 ? xDistance : -xDistance;yDistance = yDistance >= 0 ? yDistance : -yDistance;// 如果兩個合并區域相交了,返回trueif(xDistance < ((float)(lastColumn - firstColumn)/2 + (float)(cLastColumn - cFirstColumn)/2)&& yDistance < ((float)(lastRow - firstRow)/2 + (float)(cLastRow - cFirstRow)/2)) {return true;}return false;}).findFirst().orElse(null);// 如果沒有查找到沖突的區域,直接合并if(conflictRange == null){if(examineRange(rangeAddress)) {sheet.addMergedRegion(rangeAddress);}}// 如果合并區域沖突了,分離新增的合并區域List<CellRangeAddress> splitRangeAddr = splitRangeAddress(conflictRange,rangeAddress);if(splitRangeAddr != null) {splitRangeAddr.forEach(sra -> safeMergedRegion(sheetNo,sra));}}/*** 如果插入的目標合并區域target和sheet中已存在的合并區域source沖突,* 把target分割成多個合并區域,這些合并區域都不會和source沖突** @param source 已經存在的合并單元格區域* @param target 新增的合并單元格區域* @return target分離之后的合并單元格列表* */private List<CellRangeAddress> splitRangeAddress(CellRangeAddress source,CellRangeAddress target){List<CellRangeAddress> splitRangeAddr = null;if(source == null || target == null) {return null;}// 獲取source區域的坐標int sFirstRow = source.getFirstRow();int sLastRow = source.getLastRow() + 1;int sFirstColumn = source.getFirstColumn();int sLastColumn = source.getLastColumn() + 1;// 獲取target區域的坐標int tFirstRow = target.getFirstRow();int tLastRow = target.getLastRow() + 1;int tFirstColumn = target.getFirstColumn();int tLastColumn = target.getLastColumn() + 1;while(true){if(splitRangeAddr == null) {splitRangeAddr = new ArrayList<>();}// 如果target被切分得無法越過source合并區域,退出循環if(tFirstRow >= sFirstRow && tLastRow <= sLastRow&& tFirstColumn >= sFirstColumn && tLastColumn <= sLastColumn) {break;}// 只考慮Y坐標,當source的最大Y坐標sLastRow在開區間(tFirstRow,tLastRow)if(sLastRow > tFirstRow && sLastRow < tLastRow){CellRangeAddress address =new CellRangeAddress(sLastRow,tLastRow - 1,tFirstColumn,tLastColumn - 1);tLastRow = sLastRow;if(examineRange(address)) {splitRangeAddr.add(address);}}// 只考慮Y坐標,當source的最小Y坐標sFirstRow在開區間(tFirstRow,tLastRow)if(sFirstRow > tFirstRow && sFirstRow < tLastRow){CellRangeAddress address =new CellRangeAddress(tFirstRow,sFirstRow - 1,tFirstColumn,tLastColumn - 1);tFirstRow = sFirstRow;if(examineRange(address)) {splitRangeAddr.add(address);}}// 只考慮X坐標,當source的最小X坐標sFirstColumn在開區間(tFirstColumn,tLastColumn)if(sFirstColumn > tFirstColumn && sFirstColumn < tLastColumn){CellRangeAddress address =new CellRangeAddress(tFirstRow,tLastRow - 1,tFirstColumn,sFirstColumn - 1);tFirstColumn = sFirstColumn;if(examineRange(address)) {splitRangeAddr.add(address);}}// 只考慮X坐標,當source的最大X坐標sLastColumn在開區間(tFirstColumn,tLastColumn)if(sLastColumn > tFirstColumn && sLastColumn < tLastColumn){CellRangeAddress address =new CellRangeAddress(tFirstRow,tLastRow - 1,sLastColumn,tLastColumn - 1);tLastColumn = sLastColumn;if(examineRange(address)) {splitRangeAddr.add(address);}}}return splitRangeAddr;}// 檢查合并區域private boolean examineRange(CellRangeAddress address){if(address == null || !examine()) {return false;}int firstRowNum = address.getFirstRow();int lastRowNum = address.getLastRow();int firstColumnNum = address.getFirstColumn();int lastColumnNum = address.getLastColumn();if(firstRowNum == lastRowNum && firstColumnNum == lastColumnNum) {return false;}return true;}private void exception() throws EncryptedDocumentException, IOException {if(ex != null){if(ex instanceof EncryptedDocumentException) {throw new EncryptedDocumentException("無法讀取的加密文件");} else if(ex instanceof IOException) {throw new IOException(ex);} else {return;}}}/*** 把sheet[sheetNo]當中所有的行從startRow位置開始,* 全部下移moveNum數量的位置,并且在騰出的空間當中創建新行** 應該使用本方法而不是采用sheet.shiftRows()和sheet.createRow(),* 主要是因為插入一段行的時候會進行如下步驟:* 第一:使用shiftRows騰出空間* 第二:使用createRow(position)從position開始創建行* 但是這樣,后面下移的行的合并單元格會部分消失,* 并且新創建的行的合并單元格并沒有消失,這是因為sheet當中的* 大于position的CellRangeAddress并沒有跟著下移。* 而使用本方法下移并且在中間自動插入行,新插入的行不會含有任何合并單元格,* 并且原來的合并單元格也不會消失。** @param sheetNo 需要操作的Sheet的編號* @param startRow 移動的Row區間的起始位置* @param moveNum 移動的行數* */public synchronized void shiftAndCreateRows(int sheetNo,int startRow,int moveNum){if(!examine() || !initSheet(sheetNo))return;// 復制當前需要操作的sheet到一個臨時的sheetSheet tempSheet = workbook.cloneSheet(sheetNo);// 獲取臨時sheet在workbook當中的索引int tempSheetNo = workbook.getSheetIndex(tempSheet);// 得到臨時sheet的第一個row的索引int firstRowNum = tempSheet.getFirstRowNum();// 得到臨時sheet的最后一個row的索引int lastRowNum = tempSheet.getLastRowNum();if(!clearSheet(sheetNo)){return;}if (startRow <= lastRowNum){for(int i= firstRowNum;i <= lastRowNum - firstRowNum + moveNum + 1;i++) {sheet.createRow(i);}}else {for(int i= firstRowNum;i <= startRow + moveNum + 1;i++) {sheet.createRow(i);}}for(int i= firstRowNum;i <= lastRowNum;i++){if(i < startRow) {copyRow(tempSheetNo,tempSheet.getRow(i),sheetNo,sheet.getRow(i),true,true);}// 到達需要插入的索引的位置,需要留出moveNum空間的行else {copyRow(tempSheetNo,tempSheet.getRow(i),sheetNo,sheet.getRow(i + moveNum),true,true);}}settingColumnWidth(tempSheetNo,sheetNo);// 刪除臨時的sheetworkbook.removeSheetAt(tempSheetNo);}/*** 把sheet[sheetNo]當中所有的列從startColumn位置開始,* 全部右移moveNum數量的位置,并且在騰出的空間當中創建新列** @param sheetNo 需要操作的Sheet的編號* @param startColumn 移動的列區間的起始位置* @param moveNum 移動的列數* */public synchronized void shiftAndCreateColumns(int sheetNo,int startColumn,int moveNum){if(!examine() || !initSheet(sheetNo))return;// 復制當前需要操作的sheet到一個臨時的sheetSheet tempSheet = workbook.cloneSheet(sheetNo);// 獲取臨時sheet在workbook當中的索引int tempSheetNo = workbook.getSheetIndex(tempSheet);// 得到臨時sheet的第一個row的索引int firstRowNum = tempSheet.getFirstRowNum();// 得到臨時sheet的最后一個row的索引int lastRowNum = tempSheet.getLastRowNum();if(!clearSheet(sheetNo)){return;}for(int i = firstRowNum;i <= lastRowNum;i++){Row row = tempSheet.getRow(i);if(row != null){int addNum = row.getLastCellNum() + moveNum;for(int j = 0;j < moveNum;j++){row.createCell(addNum);}for(int j = 0;j <= row.getLastCellNum();j++){if(j <= startColumn) {copyColumn(tempSheetNo,j,sheetNo,j,true);} else {copyColumn(tempSheetNo,j,sheetNo,j + moveNum,true);}}}}List<CellRangeAddress> crds = tempSheet.getMergedRegions();if(crds == null) {return;}crds.forEach(crd -> {int firstColumn;int lastColumn;if((lastColumn = crd.getLastColumn()) <= startColumn) {safeMergedRegion(sheetNo,crd);} else if((firstColumn = crd.getFirstColumn()) <= startColumn){if(lastColumn > startColumn){CellRangeAddress range = new CellRangeAddress(crd.getFirstRow(),crd.getLastRow(),firstColumn,startColumn);if(examineRange(range)) {safeMergedRegion(sheetNo,range);}range = new CellRangeAddress(crd.getFirstRow(),crd.getLastRow(),startColumn + moveNum + 1,lastColumn + moveNum);if(examineRange(range)) {safeMergedRegion(sheetNo,range);}}}else if(firstColumn > startColumn){CellRangeAddress range = new CellRangeAddress(crd.getFirstRow(),crd.getLastRow(),firstColumn + moveNum,lastColumn + moveNum);if(examineRange(range)) {safeMergedRegion(sheetNo,range);}}});// 刪除臨時的sheetworkbook.removeSheetAt(tempSheetNo);}/*** 移除掉行區域** @param sheetNo 需要操作的Sheet的編號* @param startRow 起始行* @param endRow 結束行* */public synchronized void removeRowArea(int sheetNo,int startRow,int endRow){if(!examine() || !initSheet(sheetNo) || startRow > endRow)return;// 復制當前需要操作的sheet到一個臨時的sheetSheet tempSheet = workbook.cloneSheet(sheetNo);// 獲取臨時sheet在workbook當中的索引int tempSheetNo = workbook.getSheetIndex(tempSheet);// 得到臨時sheet的第一個row的索引int firstRowNum = tempSheet.getFirstRowNum();// 得到臨時sheet的最后一個row的索引int lastRowNum = tempSheet.getLastRowNum();// 清空sheetif(!clearSheet(sheetNo)){return;}int delNum = endRow - startRow + 1;for(int i = firstRowNum;i <= lastRowNum;i++){Row fromRow = tempSheet.getRow(i);Row toRow = sheet.createRow(i);if(i < startRow) {copyRow(tempSheetNo,fromRow,sheetNo,toRow,true,false);} else {copyRow(tempSheetNo,tempSheet.getRow(i + delNum),sheetNo,toRow,true,false);}}List<CellRangeAddress> crds = tempSheet.getMergedRegions();if(crds == null) {return;}crds.forEach(crd -> {if(crd != null){int firstMergedRow = crd.getFirstRow();int lastMergedRow = crd.getLastRow();int firstMergedColumn = crd.getFirstColumn();int lastMergedClolunm = crd.getLastColumn();if(lastMergedRow < startRow) {safeMergedRegion(sheetNo,crd);} else if(lastMergedRow >= startRow){if(lastMergedRow <= endRow){if(firstMergedRow < startRow){mergedRegion(sheetNo,firstMergedRow,startRow - 1,firstMergedColumn,lastMergedClolunm);}}else if(lastMergedRow > endRow){if(firstMergedRow < startRow){mergedRegion(sheetNo,firstMergedRow,lastMergedRow - delNum,firstMergedColumn,lastMergedClolunm);}else if(firstMergedRow >= startRow && firstMergedRow <= endRow){mergedRegion(sheetNo,endRow + 1 - delNum,lastMergedRow - delNum,firstMergedColumn,lastMergedClolunm);}else if(firstMergedRow > endRow){mergedRegion(sheetNo,firstMergedRow - delNum,lastMergedRow - delNum,firstMergedColumn,lastMergedClolunm);}}}}});settingColumnWidth(tempSheetNo,sheetNo);// 刪除臨時的sheetworkbook.removeSheetAt(tempSheetNo);}/*** 移除掉列區域** @param sheetNo 需要操作的Sheet的編號* @param startCol 起始列* @param endCol 結束列* */public synchronized void removeColumnArea(int sheetNo,int startCol,int endCol){if(!examine() || !initSheet(sheetNo) || startCol > endCol)return;// 復制當前需要操作的sheet到一個臨時的sheetSheet tempSheet = workbook.cloneSheet(sheetNo);// 獲取臨時sheet在workbook當中的索引int tempSheetNo = workbook.getSheetIndex(tempSheet);// 得到臨時sheet的第一個row的索引int firstRowNum = tempSheet.getFirstRowNum();// 得到臨時sheet的最后一個row的索引int lastRowNum = tempSheet.getLastRowNum();if(!clearSheet(sheetNo)){return;}for(int i = firstRowNum;i <= lastRowNum;i++){Row row = tempSheet.getRow(i);if(row != null){for(int j = 0;j < row.getLastCellNum();j++){// 到達刪除區間之前正常復制if(j < startCol) {copyColumn(tempSheetNo,j,sheetNo,j,true);}// 到達刪除區間后,跳過區間長度復制else {copyColumn(tempSheetNo,j + endCol - startCol + 1,sheetNo,j,true);}}}}List<CellRangeAddress> crds = tempSheet.getMergedRegions();if(crds == null) {return;}crds.forEach(crd -> {int delColNum = endCol - startCol + 1;int firstMergedRow = crd.getFirstRow();int lastMergedRow = crd.getLastRow();int firstMergedColumn = crd.getFirstColumn();int lastMergedClolunm = crd.getLastColumn();if(lastMergedClolunm < startCol) {safeMergedRegion(sheetNo,crd);} else if(lastMergedClolunm >= startCol){if(lastMergedClolunm <= endCol){if(firstMergedColumn < startCol){mergedRegion(sheetNo,firstMergedRow,lastMergedRow,firstMergedColumn,startCol - 1);}}else if(lastMergedClolunm > endCol){if(firstMergedColumn < startCol){mergedRegion(sheetNo,firstMergedRow,lastMergedRow,firstMergedColumn,lastMergedClolunm - delColNum);}else if(firstMergedColumn >= startCol && firstMergedColumn <= endCol){mergedRegion(sheetNo,firstMergedRow,lastMergedRow,endCol + 1 - delColNum,lastMergedClolunm - delColNum);}else if(firstMergedColumn > endCol){mergedRegion(sheetNo,firstMergedRow,lastMergedRow,firstMergedColumn - delColNum,lastMergedClolunm -delColNum);}}}});// 刪除臨時的sheetworkbook.removeSheetAt(tempSheetNo);}private void settingColumnWidth(int sourceSheetNo,int sheetNo){if(sourceSheetNo < 0 || sourceSheetNo > workbook.getNumberOfSheets() ||sheetNo < 0 || sheetNo > workbook.getNumberOfSheets()) {return;}List<Row> rows = new ArrayList<>();for(int i = sheet.getFirstRowNum();i <= sheet.getLastRowNum();i++){Row row = sheet.getRow(i);if(row != null) {rows.add(row);}}Row maxColumnRow = rows.stream().max((r1,r2) -> {if (r1 == null && r2 == null) {return 0;}if (r1 == null) {return 1;}if (r2 == null) {return -1;}if (r1.getLastCellNum() == r2.getLastCellNum()) {return 0;}if (r1.getLastCellNum() > r2.getLastCellNum()) {return 1;} else {return -1;}}).filter(r -> r != null).orElse(null);if(maxColumnRow != null){int maxColumn = maxColumnRow.getLastCellNum();for (int i = 0; i < maxColumn; i++) {workbook.getSheetAt(sheetNo).setColumnWidth(i,workbook.getSheetAt(sourceSheetNo).getColumnWidth(i));}}}/*** 清除掉sheet,清除不是刪除,只是會清除所有* 的列的值和和合并單元格** @param sheetNo 需要操作的Sheet的編號* @return boolean true-成功 false-失敗* */public synchronized boolean clearSheet(int sheetNo){if(!examine()) {return false;}int sheetNum;if(sheetNo < 0 || sheetNo > (sheetNum = workbook.getNumberOfSheets())) {return false;}for(int i = 0;i < sheetNum;i++){if(i == sheetNo){String sheetName = workbook.getSheetName(i);workbook.removeSheetAt(i);workbook.createSheet(sheetName);}if(i > sheetNo){int offset = i - sheetNo;String sheetName = workbook.getSheetName(i-offset);Sheet newSheet = workbook.cloneSheet(i-offset);workbook.removeSheetAt(i-offset);workbook.setSheetName(workbook.getSheetIndex(newSheet),sheetName);}}if(!initSheet(sheetNo)) {return false;}return true;}/*** 存儲Excel** @param path 存儲路徑* @throws IOException*/public void save(String path) throwsIOException {exception();if(!examine())return;try (FileOutputStream fos = new FileOutputStream(path)){workbook.write(fos) ;}}/*** 返回Excel的字節數組** @return byte[]*/public byte[] getBytes(){if(!examine())return null;try(ByteArrayOutputStream ops = new ByteArrayOutputStream()){workbook.write(ops);return ops.toByteArray();} catch (IOException e) {e.printStackTrace();}return null;}/*** 返回Workbook** @return Workbook* @throws IOException* */public Workbook getWorkbook()throws IOException {exception();return workbook;}/*** @return sheet的數量* */public int getSheetNum(){return workbook.getNumberOfSheets();}/*** 返回sheet的行數量** @param sheetNo 需要操作的Sheet的編號* @return int 行數量* */public int getSheetRowNum(int sheetNo){if(!examine() || !initSheet(sheetNo))return 0;return sheets[sheetNo].getLastRowNum();}/*** 設置excel的縮放率** @param zoom 縮放率* */public void setZoom(int zoom){if(!examine() || !initSheet(workbook.getSheetIndex(sheet)))return;for (int i = 0; i < sheets.length; i++) {sheets[i].setZoom(zoom);}}@Overridepublic boolean equals(Object o){if(o == null)return false;if(o == this)return true;if(!(o instanceof ExcelTemplate))return false;if(examine() ^ ((ExcelTemplate)o).examine())return false;return Objects.equals(path,((ExcelTemplate)o).path);}@Overridepublic int hashCode(){int hash = Objects.hashCode(path);return hash >>> 16 ^ hash;}@Overridepublic String toString(){return "ExcelTemplate from " + path + " is " +(examine() ? "effective" : "invalid");} }3.1實體類1
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/*** @Author:Mr.zhj* @Date:2022/5/20 10:01* @Description:*/@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ExcelImport {/** 字段名稱 */String value();/** 導出映射,格式如:0-未知;1-男;2-女 */String kv() default "";/** 是否為必填字段(默認為非必填) */boolean required() default false;/** 最大長度(默認255) */int maxLength() default 255;/** 導入唯一性驗證(多個字段則取聯合驗證) */boolean unique() default false;}3.2實體類2
package com.yss.datamiddle.entity.util;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/*** @Author:Mr.zhj* @Date:2022/5/20 9:57* @Description:*/@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME)public @interface ExcelExport {/** 字段名稱 */String value();/** 導出排序先后: 數字越小越靠前(默認按Java類字段順序導出) */int sort() default 0;/** 導出映射,格式如:0-未知;1-男;2-女 */String kv() default "";/** 導出模板示例值(有值的話,直接取該值,不做映射) */String example() default "";}3.3實體類3
package com.yss.datamiddle.entity.util;import java.util.LinkedHashMap;/*** @Author:Mr.zhj* @Date:2022/5/20 9:56* @Description:*/ public class ExcelClassField {/** 字段名稱 */private String fieldName;/** 表頭名稱 */private String name;/** 映射關系 */private LinkedHashMap<String, String> kvMap;/** 示例值 */private Object example;/** 排序 */private int sort;/** 是否為注解字段:0-否,1-是 */private int hasAnnotation;public String getFieldName() {return fieldName;}public void setFieldName(String fieldName) {this.fieldName = fieldName;}public String getName() {return name;}public void setName(String name) {this.name = name;}public LinkedHashMap<String, String> getKvMap() {return kvMap;}public void setKvMap(LinkedHashMap<String, String> kvMap) {this.kvMap = kvMap;}public Object getExample() {return example;}public void setExample(Object example) {this.example = example;}public int getSort() {return sort;}public void setSort(int sort) {this.sort = sort;}public int getHasAnnotation() {return hasAnnotation;}public void setHasAnnotation(int hasAnnotation) {this.hasAnnotation = hasAnnotation;} }4.control層調用
/*** 服務管理-導出* @return {@link ResponseResult}*/@ApiOperation("服務管理-導出")@PostMapping("export")public void export(HttpServletResponse response,@RequestBody @Validated ServiceInfoExportReq serviceInfoExportReq)throws UnsupportedEncodingException {log.info("服務管理-導出" + " serviceInfoExportReq:{" + serviceInfoExportReq + "}");List<ParamEntity> paramEntityList=serviceInfoService.export(serviceInfoExportReq);// 加載導出模板,excel模板的項目中路徑ExcelTemplate excel = new ExcelTemplate("excelTemplate/service.xlsx");if (!excel.examine()) {return;}// 使用一個Map來存儲所有的行區域,// 每個行區域對應Map的一個鍵LinkedHashMap<Integer, LinkedList<String>> rows = new LinkedHashMap<>();// 創建第一個行區域里面填充的值,ExcelTemplate會按從左至右,// 從上往下的順序,挨個填充區域里面的${},所以創建的時候注意順序就好for(int i=1;i<paramEntityList.size()+1;i++){LinkedList<String> list=new LinkedList();list.add(paramEntityList.get(i-1).getColumnsName());list.add(paramEntityList.get(i-1).getColumnsCode());list.add("");list.add(paramEntityList.get(i-1).getColumnsType());rows.put(i,list);}// 創建需要填充替換的值 // ${參數名} // Map<String, String> fill = new HashMap<>(); // //項目名稱 // fill.put("projectName", "測試項目"); // //項目編號 // fill.put("projectSn", "HT2021"); // //客戶名稱 // fill.put("keHuName", "股份有限公司"); // //客戶聯系人 // fill.put("ContactName", "聯系人");String fileName = "接口服務.xlsx";//創建文件名(改)String fileNameURL = URLEncoder.encode(fileName, "UTF-8");response.setContentType("octets/stream");response.setHeader("Content-disposition", "attachment;filename=" + fileNameURL + ";" + "filename*=utf-8''" + fileNameURL);response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");try {// 第一個參數,需要操作的sheet的索引// 第二個參數,需要復制的區域的第一行索引// 第三個參數,需要復制的區域的最后一行索引// 第四個參數,需要插入的位置的索引// 第五個參數,填充行區域中${}的值// 第六個參數,是否需要刪除原來的區域// 需要注意的是,行的索引一般要減一excel.addRowByExist(0,6,6,7,rows,true); // 第一個參數,需要操作的sheet的索引// 第二個參數,替換sheet當中${<變量的值>}的值 // excel.fillVariable(2, fill);try (OutputStream os = response.getOutputStream()) {os.write(excel.getBytes());os.flush();}} catch (IOException e) {e.printStackTrace();}}?excel模板
?輸出excel
?5.excel位置
?
?
總結
以上是生活随笔為你收集整理的excel自定义表格poi导出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「LG2114」起床困难综合症
- 下一篇: css 实现超出两行、多行文字省略号显示