iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >如何使用Java 实现excel模板导出---多sheet导出?
  • 267
分享到

如何使用Java 实现excel模板导出---多sheet导出?

javaspringboot 2023-10-08 10:10:51 267人浏览 薄情痞子
摘要

实现多个sheet的excel导出功能 效果展示: maven依赖 org.apache.poipoi3.17org.apache.poipoi-ooxml3.17 相关工具类 **此处省略异常处理

实现多个sheet的excel导出功能

效果展示:
在这里插入图片描述

maven依赖

<dependency><groupId>org.apache.poigroupId><artifactId>poiartifactId><version>3.17version>dependency><dependency><groupId>org.apache.poigroupId><artifactId>poi-ooxmlartifactId><version>3.17version>dependency>

相关工具类
**此处省略异常处理类

ExcelReportUtil 类

import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.poi.ss.usermodel.*;import org.apache.poi.ss.util.CellRangeAddress;import java.math.BigDecimal;import java.util.*;public class ExcelReportUtil {private static Log logger = LogFactory.getLog(ExcelReportUtil.class);public static void cloneRow(Sheet sheet, Row srcRow, Row destRow) {if (sheet == null || srcRow == null || destRow == null)return;Set mergedRegions = new HashSet();destRow.setHeight(srcRow.getHeight());if (srcRow.getFirstCellNum() >= 0 && srcRow.getLastCellNum() >= 0) {            for (int i = srcRow.getFirstCellNum(), j = srcRow.getLastCellNum(); i <= j; i++) {Cell srcCell = srcRow.getCell(i);Cell destCell = destRow.getCell(i);                if (srcCell != null) {                logger.debug("cell is found at col[" + i +                 "], will be cloned to the destRow");                    if (destCell == null) {                        destCell = destRow.createCell(i);                    }                    cloneCell(srcCell, destCell);                    CellRangeAddress mergedRegion = getMergedRegion(sheet, srcRow.getRowNum(),                    srcCell.getColumnIndex());                    if (mergedRegion != null) {                    CellRangeAddress newMergedRegion = new CellRangeAddress(                    destRow.getRowNum(),                     destRow.getRowNum() + mergedRegion.getLastRow() - mergedRegion.getFirstRow(),                     mergedRegion.getFirstColumn(),                     mergedRegion.getLastColumn());                        if (isNewMergedRegion(newMergedRegion, mergedRegions)) {                        logger.debug("CellRangeAddress is found at col[" + i +                         "], will be cloned to the destRow");mergedRegions.add(newMergedRegion);sheet.addMergedRegion(newMergedRegion);                        }                    }                }            }}}public static CellRangeAddress getMergedRegion(Sheet sheet, int rowNum, int colNum) {        for (int i = 0, c = sheet.getNumMergedRegions(); i < c; i++) {            CellRangeAddress merged = sheet.getMergedRegion(i);            if (isRangeContainsCell(merged, rowNum, colNum)) {                return merged;            }        }        return null;    }    public static boolean isRangeContainsCell(CellRangeAddress range, int row, int col) {        if ((range.getFirstRow() <= row) && (range.getLastRow() >= row)                && (range.getFirstColumn() <= col)                && (range.getLastColumn() >= col)) {            return true;        }        return false;    }            private static boolean isNewMergedRegion(CellRangeAddress region,            Collection mergedRegions) {        for (Iterator iterator = mergedRegions.iterator(); iterator.hasNext();) {            CellRangeAddress cellRangeAddress = (CellRangeAddress) iterator.next();            if (areRegionsEqual(cellRangeAddress, region)) {                return false;            }        }        return true;    }            public static boolean areRegionsEqual(CellRangeAddress region1,            CellRangeAddress region2) {        if ((region1 == null && region2 != null)                || (region1 != null && region2 == null)) {            return false;        }        if (region1 == null) {            return true;        }        return (region1.getFirstColumn() == region2.getFirstColumn()                && region1.getLastColumn() == region2.getLastColumn()                && region1.getFirstRow() == region2.getFirstRow()                 && region2.getLastRow() == region2.getLastRow());    }            public static void cloneCell(Cell srcCell, Cell destCell) {if (srcCell == null || destCell == null)return;destCell.setCellStyle(srcCell.getCellStyle());switch (srcCell.getCellTypeEnum()) {case NUMERIC :destCell.setCellValue(srcCell.getNumericCellValue());break;case STRING :destCell.setCellValue(srcCell.getRichStrinGCellValue());break;case FORMULA :destCell.setCellFormula(srcCell.getCellFormula());break;case ERROR:destCell.setCellErrorValue(srcCell.getErrorCellValue());break;case BOOLEAN:destCell.setCellValue(srcCell.getBooleanCellValue());break;default :destCell.setCellType(CellType.BLANK);break;}}            public static void setCellValue(Cell cell, Object value) {    if (cell == null)    return;    if (value == null) {    cell.setCellType(CellType.BLANK);    } else if (value instanceof Calendar) {    cell.setCellValue((Calendar) value);    //Date格式化日期输出} else if (value instanceof Date) {//cell.setCellValue((Date) value);//cell.setCellValue(BaseUtils.Date2String((Date)value, CommonConstants.FORMAT_Date));cell.setCellValue(BaseUtils.Date2String((Date)value, "yyyy-MM-dd HH:mm:ss"));} else if (value instanceof Number) {setCellValue(cell, (Number) value);} else if (value instanceof String) {cell.setCellValue((String) value);} else {logger.warn("value type [" + value.getClass().getName() + "] is not directly supported, will be processed as String");cell.setCellValue((String) value.toString());}    }    private static void setCellValue(Cell cell, Number value) {double doubleContent = 0.0;if (value instanceof Byte) {doubleContent = (Byte) value;} else if (value instanceof Double) {doubleContent = (Double) value;} else if (value instanceof Float) {doubleContent = (Float) value;//BigDecimal转换为Double}else if (value instanceof BigDecimal) {doubleContent = TypeCaseHelper.convert2Double(value);} else if (value instanceof Integer) {float tmp = (Integer) value;doubleContent = tmp;} else if (value instanceof Long) {float tmp = (Long) value;doubleContent = tmp;} else if (value instanceof Short) {short tmp = (Short) value;doubleContent = tmp;} else {throw new XLSReportException("value type [" + value.getClass().getName() + "] can not be processed as double");}cell.setCellValue(doubleContent);}public static String getCellStringValue(Cell cell) {String cellStringValue = null;switch (cell.getCellTypeEnum()) {case NUMERIC:cellStringValue = cell.getNumericCellValue() + "";break;case STRING:cellStringValue = cell.getStringCellValue();break;case BOOLEAN:cellStringValue = cell.getBooleanCellValue() + "";break;default :logger.warn("can not get the string value of a cell whose type is " + cell.getCellTypeEnum());cellStringValue = "";break;}return cellStringValue;}public static void removeComment(Sheet sheet, Comment comment) {if (sheet != null && comment != null) {sheet.getRow(comment.getRow()).getCell(comment.getColumn()).removeCellComment();}}}

excel 接口

import org.apache.poi.ss.usermodel.Sheet;import java.util.Map;public interface ExcelProcessor{void init();boolean isInited();void process(Sheet sheet, Map dataSource);}

实现类

import com.alibaba.fastJSON.jsON;import com.alibaba.fastjson.JSONException;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.ibatis.ognl.Ognl;import org.apache.ibatis.ognl.OgnlException;import org.apache.poi.ss.usermodel.*;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.Map;public class ExcelIteratorNoLastRowProcessor implements ExcelProcessor {//填充类型public static String TYPE_ID = "I";private static Log logger = LogFactory.getLog(ExcelIteratorNoLastRowProcessor.class);private boolean inited;//批注private final Comment comment;//填充数据的名称private String expression;//从第几行开始填充private int firstIndex;//填充的数据private Map<Integer, String> dataMapping;public ExcelIteratorNoLastRowProcessor(Comment comment) {this.comment = comment;}public String getExpression() {return expression;}public void setExpression(String expression) {this.expression = expression;}public int getFirstIndex() {return firstIndex;}public void setFirstIndex(int firstIndex) {this.firstIndex = firstIndex;}public Map<Integer, String> getDataMapping() {return dataMapping;}public void setDataMapping(Map<Integer, String> dataMapping) {this.dataMapping = dataMapping;}@Overridepublic void init() {try {Map<String, Object> claSSMap = new HashMap<String, Object>();classMap.put("dataMapping", Map.class);Map<String, Object> cfg = JSON.parseObject(this.comment.getString().toString(),Map.class);Object expresionCfg = cfg.get("expression");Object firstIndexCfg = cfg.get("firstIndex");Object dataMappingCfg = cfg.get("dataMapping");if (expresionCfg == null || !(expresionCfg instanceof String)) {throw new XLSReportCfgException("expresion must be configured and its type must be String");}this.expression = (String) expresionCfg;if (firstIndexCfg == null || !(firstIndexCfg instanceof Integer)) {throw new XLSReportCfgException("firstIndex must be configured and its type must be Integer");}this.firstIndex = (Integer) firstIndexCfg;if (dataMappingCfg == null || !(dataMappingCfg instanceof Map)) {throw new XLSReportCfgException("dataMapping must be configured and its type must be Map");}this.dataMapping = (Map<Integer, String>) dataMappingCfg;this.inited = true;} catch (JSONException e) {throw new XLSReportCfgException("the comment configuration at [" +comment.getRow() + "," + comment.getColumn() + "] " + comment.getString().toString() +" is error", e);}}@Overridepublic boolean isInited() {return this.inited;}@Overridepublic void process(Sheet sheet, Map dataSource) {try {if (!isInited())throw new XLSReportException("the CommentProcessor has not inited yet");//从dataSource中找到填充目标名称Object content = Ognl.getValue(this.expression, dataSource);if (content == null) {content = Collections.EMPTY_LIST;}if (!(content instanceof Iterable)) {content = Arrays.asList(content);}int index = 0;boolean isAddRow = false;for (Object element : (Iterable) content) {//clone rowlogger.debug("clone the row at index[" + (this.firstIndex + index + 1) + "] to the new row at index[" + (this.firstIndex + index) + "]");ExcelReportUtil.cloneRow(sheet, sheet.getRow(this.firstIndex + index + 1), sheet.createRow(this.firstIndex + index));//获取填充行Row aimedRow = sheet.getRow(this.firstIndex + index);//fill datafor (Integer key : this.dataMapping.keySet()) {int cellIndex = key;//获取第一行的数据Map rowDS = new ExcelDataSource(element).getData();rowDS.put("index", index);Cell aimedCell = aimedRow.getCell(cellIndex);if (aimedCell == null)aimedCell = aimedRow.createCell(cellIndex);//找到列对应的数据Object value = Ognl.getValue(this.dataMapping.get(key), rowDS);//样式if(Boolean.parseBoolean(rowDS.get("isBolded") == null ? "":rowDS.get("isBolded").toString())){Workbook workbook = sheet.getWorkbook();CellStyle cellStyle = workbook.createCellStyle();Font font = workbook.createFont();//font.setBoldweight(Font.BOLDWEIGHT_BOLD);font.setBold(true);cellStyle.setFont(font);aimedCell.setCellStyle(cellStyle);}logger.debug("set the value of cell[" + (this.firstIndex + index) + ", " + cellIndex + "] to " + value);//给列填值ExcelReportUtil.setCellValue(aimedCell, value);}index++;}//remove commentExcelReportUtil.removeComment(sheet, this.comment);} catch (OgnlException e) {throw new XLSReportException("extracting data error while using OGNL expression[" +this.expression + "] with root object : " + dataSource);}}}

excel填充数据处理类

import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.util.Collections;import java.util.HashMap;import java.util.Map;public class ExcelDataSource  {private static Log logger = LogFactory.getLog(ExcelDataSource.class);private Object dataSource;public ExcelDataSource(Object dataSource) {this.dataSource = dataSource;}public Map getData() {Map ds = null;if (this.dataSource == null) {ds = Collections.emptyMap();} else if (this.dataSource instanceof Map) {ds = (Map) this.dataSource;} else {logger.debug("the type of dataSource is [" + dataSource.getClass() + "], will be transformed to Map");ds = transformPropertiesToMap(this.dataSource);}return ds;}private Map transformPropertiesToMap(Object bean) {Map properties = new HashMap();BeanInfo beanInfo;try {beanInfo = Introspector.getBeanInfo(bean.getClass());PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();for (PropertyDescriptor pd : pds) {if (!"class".equals(pd.getName())) {properties.put(pd.getName(), pd.getReadMethod().invoke(bean));}}} catch (Exception e) {throw new XLSReportException(e);}return properties;}}

excel填充处理类

import com.alibaba.fastjson.JSON;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.poi.ss.usermodel.*;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class ExcelReportFiller {private static final Log logger = LogFactory.getLog(ExcelReportFiller.class);public void fill(Workbook template, Map dataSource) {int sheetCount = template.getNumberOfSheets();for (int i = 0; i < sheetCount; i++) {logger.debug("scan the sheet at index[" + i + "]");fillSheet(template.getSheetAt(i), dataSource);}}public void fillSheetName(String sheetName, Workbook template,Map dataSource) {logger.debug("scan the sheet at [" + sheetName + "]");fillSheet(template.getSheet(sheetName), dataSource);}private void fillSheet(Sheet sheet, Map dataSource) {int rowCount = sheet.getLastRowNum();for (int i = 0; i <= rowCount; i++) {Row row = sheet.getRow(i);if (row != null) {int cellCount = row.getLastCellNum();for (int j = 0; j <= cellCount; j++) {Cell cell = row.getCell(j);if (cell != null ) {Comment comment = cell.getCellComment();if (comment != null) {logger.debug("comment is found at [" + i + ", " + j + "]");ExcelProcessor processor = ExcelProcessorFactory.getCommentProcessor(comment);processor.process(sheet, dataSource);//refresh rowCountrowCount = sheet.getLastRowNum();}}}}}}}

excel模板处理

import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.usermodel.WorkbookFactory;import javax.servlet.Http.httpservletRequest;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;public class ExcelReportTemplate  {private static final Log logger = LogFactory.getLog(ExcelReportTemplate.class);private final String path;private ClassLoader classLoader;public ExcelReportTemplate(String path) {this(path, (ClassLoader) null);}public ExcelReportTemplate(String path, ClassLoader classLoader) {if (path == null) {throw new IllegalArgumentException("Path must not be null");}this.path = path;if (classLoader == null) {try {classLoader = Thread.currentThread().getContextClassLoader();} catch (Throwable ex) {logger.debug("Cannot access thread context ClassLoader - falling back to system class loader", ex);classLoader = ExcelReportTemplate.class.getClassLoader();}}this.classLoader = classLoader;}public Workbook getTemplate() throws IOException, InvalidFormatException {InputStream is =new FileInputStream(this.path);if (is == null) {throw new FileNotFoundException("class path resource [" + this.path + "] cannot be opened because it does not exist");}//return new HSSFWorkbook(is);Workbook workbook = WorkbookFactory.create(is);if(is != null){is.close();}return workbook;}public Workbook getTemplate(HttpServletRequest resquest) throws IOException, InvalidFormatException {InputStream is = this.classLoader.getResourceAsStream(this.path);if (is == null) {throw new FileNotFoundException("class path resource [" + this.path + "] cannot be opened because it does not exist");}Workbook workbook = WorkbookFactory.create(is);if(is != null){is.close();}return workbook;}}

实现关键代码展示
通过模板实现导出功能

 try {            os = new FileOutputStream(excelPth);            ExcelReportCreator.createXLS(new ExcelReportTemplate(excelTempletPath),                    new ExcelDataSource(jsonMap),                    new ExcelReportFiller(),                    os);            excelFilePathName = ftpPath + fileModel.getRealFileName();        } catch (Exception e) {            log.error("导出excel文件出错" + " excel文件路径=" + excelPth + " 模板路径=" + excelTempletPath, e);            log.error("excel内容 " + jsonMap);            throw e;        } finally {            if (os != null) {                os.close();            }        }

ExcelReportCreator 中的代码

public static void createXLS(ExcelReportTemplate template,ExcelDataSource dataSource, ExcelReportFiller filler,OutputStream os) throws IOException, InvalidFormatException {Workbook workbook = template.getTemplate();filler.fill(workbook, dataSource.getData());workbook.write(os);}

导入数据案例展示
在这里插入图片描述
excel模板批注案例
每个sheet页都需要写批注,通过批注中的expression对应的值来判断是哪个sheet页的数据,从而进行填充。dataMapping中的key值指的是列序号,value值指的是填充的字段名称,通过名称找对应的数据。
在这里插入图片描述

来源地址:https://blog.csdn.net/Do_LaLi/article/details/131873298

--结束END--

本文标题: 如何使用Java 实现excel模板导出---多sheet导出?

本文链接: https://www.lsjlt.com/news/425223.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何使用Java 实现excel模板导出---多sheet导出?
    实现多个sheet的excel导出功能 效果展示: maven依赖 org.apache.poipoi3.17org.apache.poipoi-ooxml3.17 相关工具类 **此处省略异常处理...
    99+
    2023-10-08
    java spring boot
  • EasyExcel实现excel导出(多sheet)
    EasyExcel官方地址: EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy ExcelEasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。他能让你在不用考虑性能、内存...
    99+
    2023-09-03
    java 开发语言 spring boot
  • PhpSpreadsheet 实现Excel多sheet导出
     如图 最近要做一个这样的导出,一个团长对应一个sheet,然后一键导出 使用PhpOffice\PhpSpreadsheet实现   直接上代码      public function xtexport($data_arra...
    99+
    2023-09-08
    excel php PhpSpreadsheet
  • Java使用POI导出Excel(二):多个sheet
    相关文章: Java使用POI导出Excel(一):单sheet Java使用POI导出Excel(二):多个sheet 相信在大部分的web项目中都会有导出导入Excel的需求,但...
    99+
    2024-04-02
  • Java使用POI导出Excel(一):单sheet
    相关文章: Java使用POI导出Excel(一):单sheet Java使用POI导出Excel(二):多个sheet 相信在大部分的web项目中都会有导出导入Excel的需求,今...
    99+
    2024-04-02
  • Java利用POI导入Excel数据(多个sheet、模板)
    需求:根据excel模板导入数据            sheet1:1-6行为固定格式,且需要取值({xxx});7行开始为数据集合(list)            sheet2:都为固定格式,取值地方:{xxx}         1...
    99+
    2023-09-14
    excel java
  • Java导出Excel模板,导出数据到指定模板,通过模板导入数据(一)
    本文章主要是介绍阿里巴巴的easyexcel的使用 首先需要我们导入easyexcel的依赖包 com.alibaba easyexcel 2.2.7 ...
    99+
    2023-09-02
    java
  • async-excel实现多sheet异步导出方法详解
    【async-excel组件开源地址】 业务上如果需要单sheet导出,有时有需要将多个单sheet导出合并到一个excel里面此时,代码写起来也是颇为蛋碎,但是在async-exc...
    99+
    2022-12-23
    async-excel多sheet异步导出 async-excel异步导出
  • java如何使用EasyExcel导入导出excel
    这篇文章主要介绍了java如何使用EasyExcel导入导出excel,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、准备工作1、导包<!-- poi&nb...
    99+
    2023-06-15
  • 利用模板导出文件之XLSTransformer导出excel文件
    使用XLSTransformer库导出excel文件的步骤如下:1. 安装XLSTransformer库:在命令行中运行`pip i...
    99+
    2023-09-14
    excel
  • 如何实现JeecgBoot单表数据导出多sheet
    本篇内容介绍了“如何实现JeecgBoot单表数据导出多sheet”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有...
    99+
    2024-04-02
  • java如何导出excel
    小编给大家分享一下java如何导出excel,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!看代码吧~public static void&nb...
    99+
    2023-06-15
  • java使用EasyExcel导入导出excel
    目录一、准备工作 1、导包二、了解注解 1、常用注解2、@ExcelProperty注解 3、@ColumnWith注解 4、@ContentFontStyle注解 5、@Conte...
    99+
    2024-04-02
  • java如何实现Excel的导入、导出操作
    这篇文章主要为大家展示了java如何实现Excel的导入、导出操作,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。一、Excel的导入导入可采用两种方式,一种是JXL,另一种是POI,但前者不能...
    99+
    2023-05-31
    java excel
  • Java如何实现导出Excel功能
    这篇文章将为大家详细讲解有关Java如何实现导出Excel功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。刚写了个导入Excel表格,现在来写个导出,其实形式都差不多,废话不多说,贴代码&...
    99+
    2023-06-21
  • Java如何利用POI实现导入导出Excel表格
    这篇文章主要介绍“Java如何利用POI实现导入导出Excel表格”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java如何利用POI实现导入导出Excel表格”文章能帮助大家解决问题。一、Java...
    99+
    2023-07-06
  • Pandas实现自定义Excel格式并导出多个sheet表
    目录前言1.导入pandas及数据2.修改pd.to_excle方法3.构建保存方法save4.创建pd.ExcelWriter实例5.创建多个sheet表6.设置自定义列宽7.设置...
    99+
    2023-05-19
    Pandas自定义Excel格式 Pandas导出Excel表格 Pandas Excel
  • 怎么使用Java+element实现excel导入和导出
    本篇内容介绍了“怎么使用Java+element实现excel导入和导出”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!本项目是前端vue3,...
    99+
    2023-07-06
  • Java 导出Excel利器 JXLS(excel模板配置教程)
    简介 相信大家能经常性的遇到项目上各类excel的导出,简单的excel格式,用简单的poi,easyExcel等工具都能导出。但是针对复杂的excel,有固定的样式、合并单元格、动态列等各类要求,导致excel 导出需要花很大一部分精力去...
    99+
    2023-09-01
    excel java
  • 使用EasyExcel实现Excel的导入导出
    文章目录 前言一、EasyExcel是什么?二、使用步骤1.导入依赖2.编写文件上传配置3.配置表头对应实体类4.监听器编写5.控制层6.前端代码 总结 前言 在真实的开发者场景中,经常会使用excel作为数据的载体,进行...
    99+
    2023-08-17
    java
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作