java通过Excel 模板导出复杂统计类excel文档,在ruoyi前后端分离框架中的应用
生活随笔
收集整理的這篇文章主要介紹了
java通过Excel 模板导出复杂统计类excel文档,在ruoyi前后端分离框架中的应用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Hello, 大家好!
我是不作死就不會死,智商不在線,但顏值超有品的拆家隊大隊長 ——咖啡汪
一只不是在戲精,就是在戲精路上的極品二哈
前幾天剛做了java通過Excel 模板導(dǎo)出復(fù)雜統(tǒng)計類excel文檔這么一個小功能,特此記錄下,分享給需要的小伙伴
示例用的框架是nuoyi的單體前后端分離框架,開源地址:https://gitee.com/y_project/RuoYi-Vue
首先讓我們先來看一下要求:
(1)這是客戶提供的模板:
(2) 這是本汪修改后的模板:
(3)這是最終實現(xiàn)的可導(dǎo)出的excel:
pom.xml 文件引入 poi 依賴:
<!-- jxls poi Husky Yue --><dependency><groupId>org.jxls</groupId><artifactId>jxls-poi</artifactId><version>2.10.0</version></dependency><dependency><groupId>org.jxls</groupId><artifactId>jxls</artifactId><version>2.10.0</version></dependency><dependency><groupId>net.sf.jxls</groupId><artifactId>jxls-core</artifactId><version>1.0.6</version></dependency>service
/*** 根據(jù)考勤統(tǒng)計模板導(dǎo)出部門考勤統(tǒng)計記錄** @param countDo*/@Overridepublic AjaxResult exportTemplateProvinceAreaData(CountDo countDo) {String fileName = "";AjaxResult result = new AjaxResult();//查詢考勤日歷CcccCheckonworkCalendar ccccCheckonworkCalendar = new CcccCheckonworkCalendar();System.out.println("查詢?nèi)掌?#34; +DateUtils.getDateByStandardString(countDo.getStartDate()) );ccccCheckonworkCalendar.setCalendarDate(DateUtils.getDateByStandardString(countDo.getStartDate()));List<CcccCheckonworkCalendar> calendars = ccccCheckonworkCalendarMapper.selectCcccCheckonworkCalendarList(ccccCheckonworkCalendar);// 獲取每個員工實際出勤天數(shù)List<EmployeeCountDo> list = ccccCheckonworkCardCountService.listEmployeeCount(countDo);if (list.size() == 0) {return result;}SysDept sysDept = sysDeptMapper.selectDeptById(countDo.getDeptId());//獲取每個員工某個月每天的全部打卡記錄List<TemplateCheckonworkCalenderCount> templateCheckonworkCalenderCountList = new ArrayList<>();CcccCheckonworkCardCountDto dto = new CcccCheckonworkCardCountDto();dto.setId(countDo.getDeptId());dto.setStartDate(countDo.getStartDate());dto.setEndDate(countDo.getEndDate());//查詢出該部門所有人員某個月全部的考勤記錄List<CcccCheckonworkCardCount> ccccCheckonworkCardCountList = ccccCheckonworkCardCountService.selectCcccCheckonworkCardCountListByCcccCheckonworkCardCountDto(dto);list.forEach(employeeCountDo -> {//某一個人當(dāng)月全部的考勤記錄List<CcccCheckonworkCardCount> list1 = ccccCheckonworkCardCountList.parallelStream().filter(i -> i.getEmployeeId() == employeeCountDo.getEmployeeId()).collect(Collectors.toList());TemplateCheckonworkCalenderCount templateCount = new TemplateCheckonworkCalenderCount();templateCount.setEmployeeId(employeeCountDo.getEmployeeId());templateCount.setEmployeeName(employeeCountDo.getEmployeeName());templateCount.setRealNum(employeeCountDo.getRealName());// 1.所有日子都記錄為公休 "×"// 2.所有上班日子都記錄為倒休 "D"calendars.stream().filter(cal -> cal.getIsRest() == 0 ).forEach(c -> {templateByZhongJiaoRest(templateCount, c);});// 3.當(dāng)天上班記錄均為正常則記為正常打卡 "/"list1.forEach(c -> {templateByZhongJiao(templateCount, c);});//將 實際出勤天數(shù)放入導(dǎo)出模板類中templateCount.setRealNum(employeeCountDo.getRealName());templateCheckonworkCalenderCountList.add(templateCount);});try {for (int i = 0; i < list.size(); i++) {templateCheckonworkCalenderCountList.get(i).setEmployeeId(i + 1L);}Map<String, Object> param = new HashMap<>();param.put("dept", sysDept.getDeptName());param.put("date", countDo.getStartDate());param.put("needNum", list.get(0).getNeedName());param.put("list", templateCheckonworkCalenderCountList);templateCheckonworkCalenderCountList.forEach(i -> {System.out.println(i.toString());});fileName = "考勤統(tǒng)計";ExcelUtil util = new ExcelUtil(CcccCheckonworkCardCount.class);result = util.downLoadExcel(fileName, env.getProperty("checkonwork.template.count", String.class), param);} catch (Exception e) {throw new ServiceException("excel export error");}return result;}工具類
package com.cccc.common.utils.poi;import java.io.*; import java.lang.reflect.Field; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors;import com.cccc.common.annotation.Excel; import com.cccc.common.annotation.Excels; import com.cccc.common.config.RuoYiConfig; import com.cccc.common.core.domain.AjaxResult; import com.cccc.common.core.text.Convert; import com.cccc.common.exception.CustomException; import com.cccc.common.utils.DictUtils; import com.cccc.common.utils.StringUtils; import com.cccc.common.utils.reflect.ReflectUtils; import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidationConstraint; import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFDataValidation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cccc.common.utils.DateUtils;import javax.servlet.http.HttpServletResponse;/*** Excel相關(guān)處理* * @author ruoyi*/ public class ExcelUtil<T> {private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);/*** Excel sheet最大行數(shù),默認(rèn)65536*/public static final int sheetSize = 65536;/*** 工作表名稱*/private String sheetName;/*** 導(dǎo)出類型(EXPORT:導(dǎo)出數(shù)據(jù);IMPORT:導(dǎo)入模板)*/private Excel.Type type;/*** 工作薄對象*/private Workbook wb;/*** 工作表對象*/private Sheet sheet;/*** 樣式列表*/private Map<String, CellStyle> styles;/*** 導(dǎo)入導(dǎo)出數(shù)據(jù)列表*/private List<T> list;/*** 注解列表*/private List<Object[]> fields;/*** 統(tǒng)計列表*/private Map<Integer, Double> statistics = new HashMap<Integer, Double>();/*** 數(shù)字格式*/private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");/*** 實體對象*/public Class<T> clazz;public ExcelUtil(Class<T> clazz){this.clazz = clazz;}public void init(List<T> list, String sheetName, Excel.Type type){if (list == null){list = new ArrayList<T>();}this.list = list;this.sheetName = sheetName;this.type = type;createExcelField();createWorkbook();}/*** 對excel表單默認(rèn)第一個索引名轉(zhuǎn)換成list* * @param is 輸入流* @return 轉(zhuǎn)換后集合*/public List<T> importExcel(InputStream is) throws Exception{return importExcel(StringUtils.EMPTY, is);}/*** 對excel表單指定表格索引名轉(zhuǎn)換成list* * @param sheetName 表格索引名* @param is 輸入流* @return 轉(zhuǎn)換后集合*/public List<T> importExcel(String sheetName, InputStream is) throws Exception{this.type = Excel.Type.IMPORT;this.wb = WorkbookFactory.create(is);List<T> list = new ArrayList<T>();Sheet sheet = null;if (StringUtils.isNotEmpty(sheetName)){// 如果指定sheet名,則取指定sheet中的內(nèi)容.sheet = wb.getSheet(sheetName);}else{// 如果傳入的sheet名不存在則默認(rèn)指向第1個sheet.sheet = wb.getSheetAt(0);}if (sheet == null){throw new IOException("文件sheet不存在");}int rows = sheet.getPhysicalNumberOfRows();if (rows > 0){// 定義一個map用于存放excel列的序號和field.Map<String, Integer> cellMap = new HashMap<String, Integer>();// 獲取表頭Row heard = sheet.getRow(0);for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++){Cell cell = heard.getCell(i);if (StringUtils.isNotNull(cell)){String value = this.getCellValue(heard, i).toString();cellMap.put(value, i);}else{cellMap.put(null, i);}}// 有數(shù)據(jù)時才處理 得到類的所有field.Field[] allFields = clazz.getDeclaredFields();// 定義一個map用于存放列的序號和field.Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();for (int col = 0; col < allFields.length; col++){Field field = allFields[col];Excel attr = field.getAnnotation(Excel.class);if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == type)){// 設(shè)置類的私有字段屬性可訪問.field.setAccessible(true);Integer column = cellMap.get(attr.name());if (column != null){fieldsMap.put(column, field);}}}for (int i = 1; i < rows; i++){// 從第2行開始取數(shù)據(jù),默認(rèn)第一行是表頭.Row row = sheet.getRow(i);T entity = null;for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()){Object val = this.getCellValue(row, entry.getKey());// 如果不存在實例則新建.entity = (entity == null ? clazz.newInstance() : entity);// 從map中得到對應(yīng)列的field.Field field = fieldsMap.get(entry.getKey());// 取得類型,并根據(jù)對象類型設(shè)置值.Class<?> fieldType = field.getType();if (String.class == fieldType){String s = Convert.toStr(val);if (StringUtils.endsWith(s, ".0")){val = StringUtils.substringBefore(s, ".0");}else{val = Convert.toStr(val);}}else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))){val = Convert.toInt(val);}else if (Long.TYPE == fieldType || Long.class == fieldType){val = Convert.toLong(val);}else if (Double.TYPE == fieldType || Double.class == fieldType){val = Convert.toDouble(val);}else if (Float.TYPE == fieldType || Float.class == fieldType){val = Convert.toFloat(val);}else if (BigDecimal.class == fieldType){val = Convert.toBigDecimal(val);}else if (Date.class == fieldType){if (val instanceof String){val = DateUtils.parseDate(val);}else if (val instanceof Double){val = DateUtil.getJavaDate((Double) val);}}if (StringUtils.isNotNull(fieldType)){Excel attr = field.getAnnotation(Excel.class);String propertyName = field.getName();if (StringUtils.isNotEmpty(attr.targetAttr())){propertyName = field.getName() + "." + attr.targetAttr();}else if (StringUtils.isNotEmpty(attr.readConverterExp())){val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());}else if (StringUtils.isNotEmpty(attr.dictType())){val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());}ReflectUtils.invokeSetter(entity, propertyName, val);}}list.add(entity);}}return list;}/*** 對list數(shù)據(jù)源將其里面的數(shù)據(jù)導(dǎo)入到excel表單* * @param list 導(dǎo)出數(shù)據(jù)集合* @param sheetName 工作表的名稱* @return 結(jié)果*/public AjaxResult exportExcel(List<T> list, String sheetName){this.init(list, sheetName, Excel.Type.EXPORT);return exportExcel();}/*** 對list數(shù)據(jù)源將其里面的數(shù)據(jù)導(dǎo)入到excel表單* * @param sheetName 工作表的名稱* @return 結(jié)果*/public AjaxResult importTemplateExcel(String sheetName){this.init(null, sheetName, Excel.Type.IMPORT);return exportExcel();}/*** 對list數(shù)據(jù)源將其里面的數(shù)據(jù)導(dǎo)入到excel表單* * @return 結(jié)果*/public AjaxResult exportExcel(){OutputStream out = null;try{// 取出一共有多少個sheet.double sheetNo = Math.ceil(list.size() / sheetSize);for (int index = 0; index <= sheetNo; index++){createSheet(sheetNo, index);// 產(chǎn)生一行Row row = sheet.createRow(0);int column = 0;// 寫入各個字段的列頭名稱for (Object[] os : fields){Excel excel = (Excel) os[1];this.createCell(excel, row, column++);}if (Excel.Type.EXPORT.equals(type)){fillExcelData(index, row);addStatisticsRow();}}String filename = encodingFilename(sheetName);out = new FileOutputStream(getAbsoluteFile(filename));wb.write(out);return AjaxResult.success(filename);}catch (Exception e){log.error("導(dǎo)出Excel異常{}", e.getMessage());throw new CustomException("導(dǎo)出Excel失敗,請聯(lián)系網(wǎng)站管理員!");}finally{if (wb != null){try{wb.close();}catch (IOException e1){e1.printStackTrace();}}if (out != null){try{out.close();}catch (IOException e1){e1.printStackTrace();}}}}/*** 根據(jù)模板導(dǎo)出數(shù)據(jù)* @param sheetName* @param sourcePath resource/template文件夾下路徑* @param beanParams* @throws Exception*/public AjaxResult downLoadExcel(String sheetName,String sourcePath, Map<String, Object> beanParams){OutputStream out = null;try{//讀取模板文件InputStream is = new FileInputStream(sourcePath);XLSTransformer transformer = new XLSTransformer();//填充模板中${}內(nèi)容Workbook workbook = transformer.transformXLS(is, beanParams);String filename = encodingFilename(sheetName);out = new FileOutputStream(getAbsoluteFile(filename));workbook.write(out);return AjaxResult.success(filename);}catch (Exception e){log.error("導(dǎo)出Excel異常{}", e.getMessage());throw new CustomException("導(dǎo)出Excel失敗,請聯(lián)系網(wǎng)站管理員!");}finally{if (wb != null){try{wb.close();}catch (IOException e1){e1.printStackTrace();}}if (out != null){try{out.close();}catch (IOException e1){e1.printStackTrace();}}}}/*** 填充excel數(shù)據(jù)* * @param index 序號* @param row 單元格行*/public void fillExcelData(int index, Row row){int startNo = index * sheetSize;int endNo = Math.min(startNo + sheetSize, list.size());for (int i = startNo; i < endNo; i++){row = sheet.createRow(i + 1 - startNo);// 得到導(dǎo)出對象.T vo = (T) list.get(i);int column = 0;for (Object[] os : fields){Field field = (Field) os[0];Excel excel = (Excel) os[1];// 設(shè)置實體類私有屬性可訪問field.setAccessible(true);this.addCell(excel, row, vo, field, column++);}}}/*** 創(chuàng)建表格樣式* * @param wb 工作薄對象* @return 樣式列表*/private Map<String, CellStyle> createStyles(Workbook wb){// 寫入各條記錄,每條記錄對應(yīng)excel表中的一行Map<String, CellStyle> styles = new HashMap<String, CellStyle>();CellStyle style = wb.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setBorderRight(BorderStyle.THIN);style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());style.setBorderLeft(BorderStyle.THIN);style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());style.setBorderTop(BorderStyle.THIN);style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());style.setBorderBottom(BorderStyle.THIN);style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());Font dataFont = wb.createFont();dataFont.setFontName("Arial");dataFont.setFontHeightInPoints((short) 10);style.setFont(dataFont);styles.put("data", style);style = wb.createCellStyle();style.cloneStyleFrom(styles.get("data"));style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);Font headerFont = wb.createFont();headerFont.setFontName("Arial");headerFont.setFontHeightInPoints((short) 10);headerFont.setBold(true);headerFont.setColor(IndexedColors.WHITE.getIndex());style.setFont(headerFont);styles.put("header", style);style = wb.createCellStyle();style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);Font totalFont = wb.createFont();totalFont.setFontName("Arial");totalFont.setFontHeightInPoints((short) 10);style.setFont(totalFont);styles.put("total", style);return styles;}/*** 創(chuàng)建單元格*/public Cell createCell(Excel attr, Row row, int column){// 創(chuàng)建列Cell cell = row.createCell(column);// 寫入列信息cell.setCellValue(attr.name());setDataValidation(attr, row, column);cell.setCellStyle(styles.get("header"));return cell;}/*** 設(shè)置單元格信息* * @param value 單元格值* @param attr 注解相關(guān)* @param cell 單元格信息*/public void setCellVo(Object value, Excel attr, Cell cell){if (Excel.ColumnType.STRING == attr.cellType()){cell.setCellType(CellType.STRING);cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());}else if (Excel.ColumnType.NUMERIC == attr.cellType()){cell.setCellType(CellType.NUMERIC);cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));}}/*** 創(chuàng)建表格樣式*/public void setDataValidation(Excel attr, Row row, int column){if (attr.name().indexOf("注:") >= 0){sheet.setColumnWidth(column, 6000);}else{// 設(shè)置列寬sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));row.setHeight((short) (attr.height() * 20));}// 如果設(shè)置了提示信息則鼠標(biāo)放上去提示.if (StringUtils.isNotEmpty(attr.prompt())){// 這里默認(rèn)設(shè)了2-101列提示.setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);}// 如果設(shè)置了combo屬性則本列只能選擇不能輸入if (attr.combo().length > 0){// 這里默認(rèn)設(shè)了2-101列只能選擇不能輸入.setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);}}/*** 添加單元格*/public Cell addCell(Excel attr, Row row, T vo, Field field, int column){Cell cell = null;try{// 設(shè)置行高row.setHeight((short) (attr.height() * 20));// 根據(jù)Excel中設(shè)置情況決定是否導(dǎo)出,有些情況需要保持為空,希望用戶填寫這一列.if (attr.isExport()){// 創(chuàng)建cellcell = row.createCell(column);cell.setCellStyle(styles.get("data"));// 用于讀取對象中的屬性Object value = getTargetValue(vo, field, attr);String dateFormat = attr.dateFormat();String readConverterExp = attr.readConverterExp();String separator = attr.separator();String dictType = attr.dictType();if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)){cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));}else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)){cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));}else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)){cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));}else if (value instanceof BigDecimal && -1 != attr.scale()){cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());}else{// 設(shè)置列類型setCellVo(value, attr, cell);}addStatisticsData(column, Convert.toStr(value), attr);}}catch (Exception e){log.error("導(dǎo)出Excel失敗{}", e);}return cell;}/*** 設(shè)置 POI XSSFSheet 單元格提示* * @param sheet 表單* @param promptTitle 提示標(biāo)題* @param promptContent 提示內(nèi)容* @param firstRow 開始行* @param endRow 結(jié)束行* @param firstCol 開始列* @param endCol 結(jié)束列*/public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,int firstCol, int endCol){DataValidationHelper helper = sheet.getDataValidationHelper();DataValidationConstraint constraint = helper.createCustomConstraint("DD1");CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);DataValidation dataValidation = helper.createValidation(constraint, regions);dataValidation.createPromptBox(promptTitle, promptContent);dataValidation.setShowPromptBox(true);sheet.addValidationData(dataValidation);}/*** 設(shè)置某些列的值只能輸入預(yù)制的數(shù)據(jù),顯示下拉框.* * @param sheet 要設(shè)置的sheet.* @param textlist 下拉框顯示的內(nèi)容* @param firstRow 開始行* @param endRow 結(jié)束行* @param firstCol 開始列* @param endCol 結(jié)束列* @return 設(shè)置好的sheet.*/public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol){DataValidationHelper helper = sheet.getDataValidationHelper();// 加載下拉列表內(nèi)容DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);// 設(shè)置數(shù)據(jù)有效性加載在哪個單元格上,四個參數(shù)分別是:起始行、終止行、起始列、終止列CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);// 數(shù)據(jù)有效性對象DataValidation dataValidation = helper.createValidation(constraint, regions);// 處理Excel兼容性問題if (dataValidation instanceof XSSFDataValidation){dataValidation.setSuppressDropDownArrow(true);dataValidation.setShowErrorBox(true);}else{dataValidation.setSuppressDropDownArrow(false);}sheet.addValidationData(dataValidation);}/*** 解析導(dǎo)出值 0=男,1=女,2=未知* * @param propertyValue 參數(shù)值* @param converterExp 翻譯注解* @param separator 分隔符* @return 解析后值*/public static String convertByExp(String propertyValue, String converterExp, String separator){StringBuilder propertyString = new StringBuilder();String[] convertSource = converterExp.split(",");for (String item : convertSource){String[] itemArray = item.split("=");if (StringUtils.containsAny(separator, propertyValue)){for (String value : propertyValue.split(separator)){if (itemArray[0].equals(value)){propertyString.append(itemArray[1] + separator);break;}}}else{if (itemArray[0].equals(propertyValue)){return itemArray[1];}}}return StringUtils.stripEnd(propertyString.toString(), separator);}/*** 反向解析值 男=0,女=1,未知=2* * @param propertyValue 參數(shù)值* @param converterExp 翻譯注解* @param separator 分隔符* @return 解析后值*/public static String reverseByExp(String propertyValue, String converterExp, String separator){StringBuilder propertyString = new StringBuilder();String[] convertSource = converterExp.split(",");for (String item : convertSource){String[] itemArray = item.split("=");if (StringUtils.containsAny(separator, propertyValue)){for (String value : propertyValue.split(separator)){if (itemArray[1].equals(value)){propertyString.append(itemArray[0] + separator);break;}}}else{if (itemArray[1].equals(propertyValue)){return itemArray[0];}}}return StringUtils.stripEnd(propertyString.toString(), separator);}/*** 解析字典值* * @param dictValue 字典值* @param dictType 字典類型* @param separator 分隔符* @return 字典標(biāo)簽*/public static String convertDictByExp(String dictValue, String dictType, String separator){return DictUtils.getDictLabel(dictType, dictValue, separator);}/*** 反向解析值字典值* * @param dictLabel 字典標(biāo)簽* @param dictType 字典類型* @param separator 分隔符* @return 字典值*/public static String reverseDictByExp(String dictLabel, String dictType, String separator){return DictUtils.getDictValue(dictType, dictLabel, separator);}/*** 合計統(tǒng)計信息*/private void addStatisticsData(Integer index, String text, Excel entity){if (entity != null && entity.isStatistics()){Double temp = 0D;if (!statistics.containsKey(index)){statistics.put(index, temp);}try{temp = Double.valueOf(text);}catch (NumberFormatException e){}statistics.put(index, statistics.get(index) + temp);}}/*** 創(chuàng)建統(tǒng)計行*/public void addStatisticsRow(){if (statistics.size() > 0){Cell cell = null;Row row = sheet.createRow(sheet.getLastRowNum() + 1);Set<Integer> keys = statistics.keySet();cell = row.createCell(0);cell.setCellStyle(styles.get("total"));cell.setCellValue("合計");for (Integer key : keys){cell = row.createCell(key);cell.setCellStyle(styles.get("total"));cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));}statistics.clear();}}/*** 編碼文件名*/public String encodingFilename(String filename){filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";return filename;}/*** 獲取下載路徑* * @param filename 文件名稱*/public String getAbsoluteFile(String filename){String downloadPath = RuoYiConfig.getDownloadPath() + filename;File desc = new File(downloadPath);if (!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}return downloadPath;}/*** 獲取bean中的屬性值* * @param vo 實體對象* @param field 字段* @param excel 注解* @return 最終的屬性值* @throws Exception*/private Object getTargetValue(T vo, Field field, Excel excel) throws Exception{Object o = field.get(vo);if (StringUtils.isNotEmpty(excel.targetAttr())){String target = excel.targetAttr();if (target.indexOf(".") > -1){String[] targets = target.split("[.]");for (String name : targets){o = getValue(o, name);}}else{o = getValue(o, target);}}return o;}/*** 以類的屬性的get方法方法形式獲取值* * @param o* @param name* @return value* @throws Exception*/private Object getValue(Object o, String name) throws Exception{if (StringUtils.isNotEmpty(name)){Class<?> clazz = o.getClass();Field field = clazz.getDeclaredField(name);field.setAccessible(true);o = field.get(o);}return o;}/*** 得到所有定義字段*/private void createExcelField(){this.fields = new ArrayList<Object[]>();List<Field> tempFields = new ArrayList<>();tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));for (Field field : tempFields){// 單注解if (field.isAnnotationPresent(Excel.class)){putToField(field, field.getAnnotation(Excel.class));}// 多注解if (field.isAnnotationPresent(Excels.class)){Excels attrs = field.getAnnotation(Excels.class);Excel[] excels = attrs.value();for (Excel excel : excels){putToField(field, excel);}}}this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());}/*** 放到字段集合中*/private void putToField(Field field, Excel attr){if (attr != null && (attr.type() == Excel.Type.ALL || attr.type() == type)){this.fields.add(new Object[] { field, attr });}}/*** 創(chuàng)建一個工作簿*/public void createWorkbook(){this.wb = new SXSSFWorkbook(500);}/*** 創(chuàng)建工作表* * @param sheetNo sheet數(shù)量* @param index 序號*/public void createSheet(double sheetNo, int index){this.sheet = wb.createSheet();this.styles = createStyles(wb);// 設(shè)置工作表的名稱.if (sheetNo == 0){wb.setSheetName(index, sheetName);}else{wb.setSheetName(index, sheetName + index);}}/*** 獲取單元格值* * @param row 獲取的行* @param column 獲取單元格列號* @return 單元格值*/public Object getCellValue(Row row, int column){if (row == null){return row;}Object val = "";try{Cell cell = row.getCell(column);if (StringUtils.isNotNull(cell)){if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA){val = cell.getNumericCellValue();if (HSSFDateUtil.isCellDateFormatted(cell)){val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式轉(zhuǎn)換}else{if ((Double) val % 1 > 0){val = new BigDecimal(val.toString());}else{val = new DecimalFormat("0").format(val);}}}else if (cell.getCellTypeEnum() == CellType.STRING){val = cell.getStringCellValue();}else if (cell.getCellTypeEnum() == CellType.BOOLEAN){val = cell.getBooleanCellValue();}else if (cell.getCellTypeEnum() == CellType.ERROR){val = cell.getErrorCellValue();}}}catch (Exception e){return val;}return val;} }總結(jié)
以上是生活随笔為你收集整理的java通过Excel 模板导出复杂统计类excel文档,在ruoyi前后端分离框架中的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对《基于机器学习的区域滑坡危险性评价方法
- 下一篇: 单片机第六次实验课——计数器实验