javascript
springboot使用jxls导出excel___(万能通用模板)--- SpringBoot导入、导出Excel文件___SpringBoot整合EasyExcel模板导出Excel
springboot使用jxls導出excel
實現思路:
首先在springBoot(或者SpringCloud)項目的默認templates目錄放入提前定義好的Excel模板,然后在具體的導出接口業務代碼里通過IO流加載到這個Excel模板文件,讀取指定的工作薄(也就是excel左下角的Sheet),接著給模板里的指定表頭填充表頭數據,接著讀取數據庫的相關數據用數據傳輸模型(DTO)封裝數據,最后循壞填充excel的數據行(逐行逐列的填充數據),最后把填充完數據的Excel文件流輸出(下載),即完成了數據庫數據按照指定Excel模板導出Excel的完整過程。廢話不多說,下面直接上代碼。
1.引入依賴
<!--springboot版本--> <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.6.RELEASE</version><relativePath /></parent><!-- jxls@excel --><dependency><groupId>org.jxls</groupId><artifactId>jxls</artifactId><version>2.3.0</version></dependency><dependency><groupId>org.jxls</groupId><artifactId>jxls-poi</artifactId><version>1.0.9</version></dependency><dependency><groupId>net.sf.jxls</groupId><artifactId>jxls-core</artifactId><version>1.0.5</version></dependency>2.excel工具類
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID;import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity;import net.sf.jxls.exception.ParsePropertyException; import net.sf.jxls.transformer.XLSTransformer;public class ExcelUtil {/*** 下載excel** @param sourcePath 模板路徑* @param beanParams excel內容* @return* @throws ParsePropertyException* @throws InvalidFormatException* @throws IOException*/public static ResponseEntity<byte[]> downLoadExcel(String sourcePath, Map<String, Object> beanParams)throws ParsePropertyException, InvalidFormatException, IOException {ByteArrayOutputStream os = new ByteArrayOutputStream();//讀取模板InputStream is =ExcelUtil.class.getClassLoader().getResourceAsStream(sourcePath);XLSTransformer transformer = new XLSTransformer();//向模板中寫入內容Workbook workbook = transformer.transformXLS(is, beanParams);//寫入成功后轉化為輸出流workbook.write(os);//配置Response信息HttpHeaders headers = new HttpHeaders();String downloadFileName = UUID.randomUUID().toString() + ".xlsx";//防止中文名亂碼downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");headers.setContentDispositionFormData("attachment", downloadFileName);headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//返回return new ResponseEntity<byte[]>(os.toByteArray(), headers, HttpStatus.CREATED); }3.controller調用
@RequestMapping("/export")//返回ResponseEntity<byte[]>使瀏覽器下載public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {//查詢參數Map<String, Object> params = new HashMap<String, Object>();//結果集List<Aip_std> list = stdService.selectAllForExportExcel(params);Map<String, Object> beanParams = new HashMap<String, Object>();beanParams.put("list", list);//下載表格return ExcelUtil.downLoadExcel("static/excel/aaa.xlsx",beanParams);}4.模板存放位置
5.模板
6.導出的excel
(萬能通用模板)— SpringBoot導入、導出Excel文件
先把項目的demo發一下,看完文章可以看一下,demo
前言:最近做項目過程中使用到了一個權限管理框架:若依,使用過程中發現他的文件導入和導出功能非常的實用,在這里特此做一個小demo跟大家分享一下。
導出:將從數據庫中查出的List列表,以參數的形式傳入模板中,即可返回Excel文件。
@ApiOperation(value = "導出",produces="application/octet-stream")@GetMapping("/exportExcel")public void exportExcel(HttpServletResponse response) throws IOException {// 查詢數據列表List<UserData> userData = dataService.selectUserData(); // 將list導入模板中ExcelUtil<UserData> util = new ExcelUtil<UserData>(UserData.class);//返回Excel文件util.exportExcel(response,userData , "角色數據");}導入:將Excel文件上傳,模板代碼會將此Excel文件轉換成List列表的形式返回,我們可以將返回的list列表插入到數據庫中。
@ApiOperation("導入")@PostMapping("/importExcel")public int importExcel(MultipartFile file) throws Exception {ExcelUtil<UserData> util = new ExcelUtil<>(UserData.class);// 將文件以流的形式傳入到模板代碼中,返回List列表List<UserData> userDataList = util.importExcel(file.getInputStream());// 將list列表插入到數據庫中int insertFlag = dataService.importUserData(userDataList);if (insertFlag == 0){throw new RuntimeException("導入失敗");}return insertFlag;}一、效果圖
1.導出Excel
打開Excel效果:
2.導入Excel
1)創建Excel
2)使用swagger導入
3)查看數據庫數據
導入成功
二、實現
1.數據庫
CREATE TABLE `data` (`name` varchar(33) DEFAULT NULL,`project` varchar(33) DEFAULT NULL,`score` int(3) DEFAULT NULL,`id` int(10) NOT NULL AUTO_INCREMENT,PRIMARY KEY (`id`),KEY `indx_data_funshu` (`score`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;
2. 代碼(東西較多,這里只粘貼核心代碼,詳情請查看詳細代碼)
1)實體類:在需要導出的字段上加入@Excel注解,name為導出后Excel的表頭
@Data @Table(name = "data") public class UserData {@Id@Excel(name = "序號")Integer id;@Excel(name = "名字")String name;@Excel(name = "課程")String project;@Excel(name = "分數")Integer score; }2)controller文件
package com.example.commonutils.controller;import com.example.commonutils.common.ExcelUtil; import com.example.commonutils.domain.UserData; import com.example.commonutils.service.DataService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;/*** @author tianzhuang*/ @Api(tags = "Excel的導入導出") @RestController public class ExportExcelController {@Autowiredprivate DataService dataService;/*** 在瀏覽器地址欄輸入此接口地址,即可導出Excel,用swagger導出是亂碼,暫未解決* @param response* @throws IOException*/@ApiOperation(value = "導出",produces="application/octet-stream")@GetMapping("/exportExcel")public void exportExcel(HttpServletResponse response) throws IOException {List<UserData> userData = dataService.selectUserData();ExcelUtil<UserData> util = new ExcelUtil<UserData>(UserData.class);util.exportExcel(response,userData , "角色數據");}/**** @param file* @return* @throws Exception*/@ApiOperation("導入")@PostMapping("/importExcel")public int importExcel(MultipartFile file) throws Exception {ExcelUtil<UserData> util = new ExcelUtil<>(UserData.class);List<UserData> userDataList = util.importExcel(file.getInputStream());int insertFlag = dataService.importUserData(userDataList);if (insertFlag == 0){throw new RuntimeException("導入失敗");}return insertFlag;} }ExcelUtil代碼
package com.example.commonutils.common;import com.example.commonutils.common.Excel.ColumnType; import com.example.commonutils.common.Excel.Type; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.*; 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 javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.*; import java.util.stream.Collectors;/*** Excel相關處理* * @author ruoyi*/ public class ExcelUtil<T> {private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);/*** Excel sheet最大行數,默認65536*/public static final int sheetSize = 65536;/*** 工作表名稱*/private String sheetName;/*** 導出類型(EXPORT:導出數據;IMPORT:導入模板)*/private Type type;/*** 工作薄對象*/private Workbook wb;/*** 工作表對象*/private Sheet sheet;/*** 樣式列表*/private Map<String, CellStyle> styles;/*** 導入導出數據列表*/private List<T> list;/*** 注解列表*/private List<Object[]> fields;/*** 統計列表*/private Map<Integer, Double> statistics = new HashMap<Integer, Double>();/*** 數字格式*/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, Type type){if (list == null){list = new ArrayList<T>();}this.list = list;this.sheetName = sheetName;this.type = type;createExcelField();createWorkbook();}/*** 對excel表單默認第一個索引名轉換成list* * @param is 輸入流* @return 轉換后集合*/public List<T> importExcel(InputStream is) throws Exception{return importExcel(StringUtils.EMPTY, is);}/*** 對excel表單指定表格索引名轉換成list* * @param sheetName 表格索引名* @param is 輸入流* @return 轉換后集合*/public List<T> importExcel(String sheetName, InputStream is) throws Exception{this.type = Type.IMPORT;this.wb = WorkbookFactory.create(is);List<T> list = new ArrayList<T>();Sheet sheet = null;if (StringUtils.isNotEmpty(sheetName)){// 如果指定sheet名,則取指定sheet中的內容.sheet = wb.getSheet(sheetName);}else{// 如果傳入的sheet名不存在則默認指向第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);}}// 有數據時才處理 得到類的所有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() == Type.ALL || attr.type() == type)){// 設置類的私有字段屬性可訪問.field.setAccessible(true);Integer column = cellMap.get(attr.name());if (column != null){fieldsMap.put(column, field);}}}for (int i = 1; i < rows; i++){// 從第2行開始取數據,默認第一行是表頭.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中得到對應列的field.Field field = fieldsMap.get(entry.getKey());// 取得類型,并根據對象類型設置值.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());}ReflectUtils.invokeSetter(entity, propertyName, val);}}list.add(entity);}}return list;}/*** 對list數據源將其里面的數據導入到excel表單* * @param response 返回數據* @param list 導出數據集合* @param sheetName 工作表的名稱* @return 結果* @throws IOException*/public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) throws IOException{response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");this.init(list, sheetName, Type.EXPORT);exportExcel(response.getOutputStream());}/*** 對list數據源將其里面的數據導入到excel表單* * @param sheetName 工作表的名稱* @return 結果*/public void importTemplateExcel(HttpServletResponse response, String sheetName) throws IOException{response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");this.init(null, sheetName, Type.IMPORT);exportExcel(response.getOutputStream());}/*** 對list數據源將其里面的數據導入到excel表單* * @return 結果*/public void exportExcel(OutputStream outputStream){try{// 取出一共有多少個sheet.double sheetNo = Math.ceil(list.size() / sheetSize);for (int index = 0; index <= sheetNo; index++){createSheet(sheetNo, index);// 產生一行Row row = sheet.createRow(0);int column = 0;// 寫入各個字段的列頭名稱for (Object[] os : fields){Excel excel = (Excel) os[1];this.createCell(excel, row, column++);}if (Type.EXPORT.equals(type)){fillExcelData(index, row);addStatisticsRow();}}wb.write(outputStream);}catch (Exception e){log.error("導出Excel異常{}", e.getMessage());}finally{if (wb != null){try{wb.close();}catch (IOException e1){e1.printStackTrace();}}if (outputStream != null){try{outputStream.close();}catch (IOException e1){e1.printStackTrace();}}}}/*** 填充excel數據* * @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);// 得到導出對象.T vo = (T) list.get(i);int column = 0;for (Object[] os : fields){Field field = (Field) os[0];Excel excel = (Excel) os[1];// 設置實體類私有屬性可訪問field.setAccessible(true);this.addCell(excel, row, vo, field, column++);}}}/*** 創建表格樣式* * @param wb 工作薄對象* @return 樣式列表*/private Map<String, CellStyle> createStyles(Workbook wb){// 寫入各條記錄,每條記錄對應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;}/*** 創建單元格*/public Cell createCell(Excel attr, Row row, int column){// 創建列Cell cell = row.createCell(column);// 寫入列信息cell.setCellValue(attr.name());setDataValidation(attr, row, column);cell.setCellStyle(styles.get("header"));return cell;}/*** 設置單元格信息* * @param value 單元格值* @param attr 注解相關* @param cell 單元格信息*/public void setCellVo(Object value, Excel attr, Cell cell){if (ColumnType.STRING == attr.cellType()){cell.setCellType(CellType.STRING);cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());}else if (ColumnType.NUMERIC == attr.cellType()){cell.setCellType(CellType.NUMERIC);cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));}}/*** 創建表格樣式*/public void setDataValidation(Excel attr, Row row, int column){if (attr.name().indexOf("注:") >= 0){sheet.setColumnWidth(column, 6000);}else{// 設置列寬sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));row.setHeight((short) (attr.height() * 20));}// 如果設置了提示信息則鼠標放上去提示.if (StringUtils.isNotEmpty(attr.prompt())){// 這里默認設了2-101列提示.setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);}// 如果設置了combo屬性則本列只能選擇不能輸入if (attr.combo().length > 0){// 這里默認設了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{// 設置行高row.setHeight((short) (attr.height() * 20));// 根據Excel中設置情況決定是否導出,有些情況需要保持為空,希望用戶填寫這一列.if (attr.isExport()){// 創建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();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 (value instanceof BigDecimal && -1 != attr.scale()){cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());}else{// 設置列類型setCellVo(value, attr, cell);}addStatisticsData(column, Convert.toStr(value), attr);}}catch (Exception e){log.error("導出Excel失敗{}", e);}return cell;}/*** 設置 POI XSSFSheet 單元格提示* * @param sheet 表單* @param promptTitle 提示標題* @param promptContent 提示內容* @param firstRow 開始行* @param endRow 結束行* @param firstCol 開始列* @param endCol 結束列*/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);}/*** 設置某些列的值只能輸入預制的數據,顯示下拉框.* * @param sheet 要設置的sheet.* @param textlist 下拉框顯示的內容* @param firstRow 開始行* @param endRow 結束行* @param firstCol 開始列* @param endCol 結束列* @return 設置好的sheet.*/public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol){DataValidationHelper helper = sheet.getDataValidationHelper();// 加載下拉列表內容DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);// 設置數據有效性加載在哪個單元格上,四個參數分別是:起始行、終止行、起始列、終止列CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);// 數據有效性對象DataValidation dataValidation = helper.createValidation(constraint, regions);// 處理Excel兼容性問題if (dataValidation instanceof XSSFDataValidation){dataValidation.setSuppressDropDownArrow(true);dataValidation.setShowErrorBox(true);}else{dataValidation.setSuppressDropDownArrow(false);}sheet.addValidationData(dataValidation);}/*** 解析導出值 0=男,1=女,2=未知* * @param propertyValue 參數值* @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 參數值* @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);}/*** 合計統計信息*/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);}}/*** 創建統計行*/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();}}/*** 獲取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() == Type.ALL || attr.type() == type)){this.fields.add(new Object[] { field, attr });}}/*** 創建一個工作簿*/public void createWorkbook(){this.wb = new SXSSFWorkbook(500);}/*** 創建工作表* * @param sheetNo sheet數量* @param index 序號*/public void createSheet(double sheetNo, int index){this.sheet = wb.createSheet();this.styles = createStyles(wb);// 設置工作表的名稱.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 日期格式轉換}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;} }3)Excel注解代碼
package com.example.commonutils.common;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.math.BigDecimal;/*** 自定義導出Excel數據注解* * @author ruoyi*/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Excel {/*** 導出時在excel中排序*/public int sort() default Integer.MAX_VALUE;/*** 導出到Excel中的名字.*/public String name() default "";/*** 日期格式, 如: yyyy-MM-dd*/public String dateFormat() default "";/*** 讀取內容轉表達式 (如: 0=男,1=女,2=未知)*/public String readConverterExp() default "";/*** 分隔符,讀取字符串組內容*/public String separator() default ",";/*** BigDecimal 精度 默認:-1(默認不開啟BigDecimal格式化)*/public int scale() default -1;/*** BigDecimal 舍入規則 默認:BigDecimal.ROUND_HALF_EVEN*/public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;/*** 導出類型(0數字 1字符串)*/public ColumnType cellType() default ColumnType.STRING;/*** 導出時在excel中每個列的高度 單位為字符*/public double height() default 14;/*** 導出時在excel中每個列的寬 單位為字符*/public double width() default 16;/*** 文字后綴,如% 90 變成90%*/public String suffix() default "";/*** 當值為空時,字段的默認值*/public String defaultValue() default "";/*** 提示信息*/public String prompt() default "";/*** 設置只能選擇不能輸入的列內容.*/public String[] combo() default {};/*** 是否導出數據,應對需求:有時我們需要導出一份模板,這是標題需要但內容需要用戶手工填寫.*/public boolean isExport() default true;/*** 另一個類中的屬性名稱,支持多級獲取,以小數點隔開*/public String targetAttr() default "";/*** 是否自動統計數據,在最后追加一行統計數據總和*/public boolean isStatistics() default false;/*** 字段類型(0:導出導入;1:僅導出;2:僅導入)*/Type type() default Type.ALL;public enum Type{ALL(0), EXPORT(1), IMPORT(2);private final int value;Type(int value){this.value = value;}public int value(){return this.value;}}public enum ColumnType{NUMERIC(0), STRING(1);private final int value;ColumnType(int value){this.value = value;}public int value(){return this.value;}} }代碼量較多,本文只放了部分代碼,可以進入demo進行詳細查看
SpringBoot整合EasyExcel模板導出Excel
創建SpringBoot項目
導入EasyExcel.jar
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.6</version> </dependency>創建Excel模板
實體類
public class FillData {private String name;@NumberFormat("##.0")private Double chinese;@NumberFormat("##.0")private Double math;@NumberFormat("##.0")private Double english;@NumberFormat("##.0")private Double number;//getter setter }Service實現
@Service public class ExcelExportServiceImpl implements ExcelExportService{//在springboot文件(application.properties)中配置模板所在的位置,例如//excel.template=E:/SpringToolSuiteForEclipseWorkSpace/PrivateApplication/EasyExcel/src/main/resources/1.xlsx@Value("${excel.template}")private String templateFileName;@Overridepublic void excelExport(HttpServletResponse response) throws IOException {// 模板注意 用{} 來表示你要用的變量 如果本來就有"{","}" 特殊字符 用"\{","\}"代替System.out.println(templateFileName);// 方案1 根據對象填充String fileName = "simpleFill" + System.currentTimeMillis() + ".xlsx";// 這里 會填充到第一個sheet, 然后文件流會自動關閉List<FillData> l = new ArrayList<>();for(Integer i = 0; i < 50; i++){FillData fillData = new FillData();fillData.setName("張三" + i+"號");fillData.setChinese(120.0+i);fillData.setEnglish(141.0+i);fillData.setMath(119.0+i);fillData.setNumber(fillData.getChinese()+fillData.getEnglish()+fillData.getMath());l.add(fillData);}response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("UTF-8");response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes(),"iso-8859-1"));EasyExcel.write(response.getOutputStream(),FillData.class).withTemplate(templateFileName).sheet().doFill(l);} }EasyExcel是import com.alibaba.excel.EasyExcel;
Service接口
public interface ExcelExportService {void excelExport(HttpServletResponse response) throws IOException;} 12345控制器Controller
@RestController public class HelloController {@Autowiredprivate ExcelExportService excelExportService;@GetMapping("/h")public void h(HttpServletResponse response) throws IOException {excelExportService.excelExport(response);} }然后訪問/h接口就可以導出一個Excel文件
總結
以上是生活随笔為你收集整理的springboot使用jxls导出excel___(万能通用模板)--- SpringBoot导入、导出Excel文件___SpringBoot整合EasyExcel模板导出Excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 端计算(1)-wasm
- 下一篇: pureftp