搜索
首页Javajava教程apache poi根据模板导出excel

apache poi根据模板导出excel

Jun 26, 2017 am 09:14 AM
apacheexcel导出模板

需要预先新建编辑好一个excel文件,设置好样式。

编辑好输出的数据,根据excel坐标一一对应。

支持列表数据输出,列表中列合并。

代码如下:

package com.icourt.util;import org.apache.commons.collections4.CollectionUtils;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.*;import org.apache.poi.ss.util.CellRangeAddress;import java.io.*;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.regex.Matcher;import java.util.regex.Pattern;/**
 * 描述:poi根据模板导出excel,根据excel坐标赋值,如(B1) */public class ExcelExportUtil {//模板mapprivate Map<String, Workbook> tempWorkbook = new HashMap<String, Workbook>();//模板输入流mapprivate Map<String, InputStream> tempStream = new HashMap<String, InputStream>();/** * 功能:按模板向Excel中相应地方填充数据     */public void writeData(String templateFilePath, Map<String, Object> dataMap, int sheetNo) throws IOException, InvalidFormatException {if (dataMap == null || dataMap.isEmpty()) {return;
        }//读取模板Workbook wbModule = getTempWorkbook(templateFilePath);//数据填充的sheetSheet wsheet = wbModule.getSheetAt(sheetNo);for (Entry<String, Object> entry : dataMap.entrySet()) {
            String point = entry.getKey();
            Object data = entry.getValue();

            TempCell cell = getCell(point, data, wsheet);//指定坐标赋值            setCell(cell, wsheet);
        }//设置生成excel中公式自动计算wsheet.setForceFormulaRecalculation(true);
    }/** * 功能:按模板向Excel中列表填充数据.只支持列合并     */public void writeDateList(String templateFilePath, String[] heads, List<Map<Integer, Object>> datalist, int sheetNo) throws IOException, InvalidFormatException {if (heads == null || heads.length <= 0 || CollectionUtils.isEmpty(datalist)) {return;
        }//读取模板Workbook wbModule = getTempWorkbook(templateFilePath);//数据填充的sheetSheet wsheet = wbModule.getSheetAt(sheetNo);//列表数据模板cellList<TempCell> tempCells = new ArrayList<TempCell>(heads.length);for (String point : heads) {
            TempCell tempCell = getCell(point, null, wsheet);//取得合并单元格位置  -1:表示不是合并单元格int pos = isMergedRegion(wsheet, tempCell.getRow(), tempCell.getColumn());if (pos > -1) {
                CellRangeAddress range = wsheet.getMergedRegion(pos);
                tempCell.setColumnSize(range.getLastColumn() - range.getFirstColumn());
            }
            tempCells.add(tempCell);
        }//赋值for (int i = 0; i < datalist.size(); i++) {//数据行Map<Integer, Object> dataMap = datalist.get(i);for (int j = 0; j < tempCells.size(); j++) {//列TempCell tempCell = tempCells.get(j);
                tempCell.setData(dataMap.get(j + 1));
                setCell(tempCell, wsheet);
                tempCell.setRow(tempCell.getRow() + 1);
            }
        }
    }/** * 功能:获取输入工作区     */private Workbook getTempWorkbook(String templateFilePath) throws IOException, InvalidFormatException {if (!tempWorkbook.containsKey(templateFilePath)) {
            InputStream inputStream = getInputStream(templateFilePath);
            tempWorkbook.put(templateFilePath, WorkbookFactory.create(inputStream));
        }return tempWorkbook.get(templateFilePath);
    }/** * 功能:获得模板输入流     */private InputStream getInputStream(String templateFilePath) throws FileNotFoundException {if (!tempStream.containsKey(templateFilePath)) {
            tempStream.put(templateFilePath, new FileInputStream((templateFilePath)));
        }return tempStream.get(templateFilePath);
    }/** * 功能:获取单元格数据,样式(根据坐标:B3)     */private TempCell getCell(String point, Object data, Sheet sheet) {
        TempCell tempCell = new TempCell();//得到列   字母String lineStr = "";
        String reg = "[A-Z]+";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(point);while (m.find()) {
            lineStr = m.group();
        }//将列字母转成列号  根据ascii转换char[] ch = lineStr.toCharArray();int column = 0;for (int i = 0; i < ch.length; i++) {char c = ch[i];int post = ch.length - i - 1;int r = (int) Math.pow(10, post);
            column = column + r * ((int) c - 65);
        }
        tempCell.setColumn(column);//得到行号reg = "[1-9]+";
        p = Pattern.compile(reg);
        m = p.matcher(point);while (m.find()) {
            tempCell.setRow((Integer.parseInt(m.group()) - 1));
        }//获取模板指定单元格样式,设置到tempCell(写列表数据的时候用)Row rowIn = sheet.getRow(tempCell.getRow());if (rowIn == null) {
            rowIn = sheet.createRow(tempCell.getRow());
        }
        Cell cellIn = rowIn.getCell(tempCell.getColumn());if (cellIn == null) {
            cellIn = rowIn.createCell(tempCell.getColumn());
        }
        tempCell.setCellStyle(cellIn.getCellStyle());
        tempCell.setData(data);return tempCell;
    }/** * 功能:给指定坐标单元格赋值     */private void setCell(TempCell tempCell, Sheet sheet) {if (tempCell.getColumnSize() > -1) {
            CellRangeAddress rangeAddress = mergeRegion(sheet, tempCell.getRow(), tempCell.getRow(), tempCell.getColumn(), tempCell.getColumn() + tempCell.getColumnSize());
            setRegionStyle(tempCell.getCellStyle(), rangeAddress, sheet);
        }

        Row rowIn = sheet.getRow(tempCell.getRow());if (rowIn == null) {
            copyRows(tempCell.getRow() - 1, tempCell.getRow() - 1, tempCell.getRow(), sheet);//复制上一行rowIn = sheet.getRow(tempCell.getRow());
        }
        Cell cellIn = rowIn.getCell(tempCell.getColumn());if (cellIn == null) {
            cellIn = rowIn.createCell(tempCell.getColumn());
        }//根据data类型给cell赋值if (tempCell.getData() instanceof String) {
            cellIn.setCellValue((String) tempCell.getData());
        } else if (tempCell.getData() instanceof Integer) {
            cellIn.setCellValue((int) tempCell.getData());
        } else if (tempCell.getData() instanceof Double) {
            cellIn.setCellValue((double) tempCell.getData());
        } else {
            cellIn.setCellValue((String) tempCell.getData());
        }//样式if (tempCell.getCellStyle() != null && tempCell.getColumnSize() == -1) {
            cellIn.setCellStyle(tempCell.getCellStyle());
        }
    }/** * 功能:写到输出流并移除资源     */public void writeAndClose(String templateFilePath, OutputStream os) throws IOException, InvalidFormatException {if (getTempWorkbook(templateFilePath) != null) {
            getTempWorkbook(templateFilePath).write(os);
            tempWorkbook.remove(templateFilePath);
        }if (getInputStream(templateFilePath) != null) {
            getInputStream(templateFilePath).close();
            tempStream.remove(templateFilePath);
        }
    }/** * 功能:判断指定的单元格是否是合并单元格     */private Integer isMergedRegion(Sheet sheet, int row, int column) {for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);int firstColumn = range.getFirstColumn();int lastColumn = range.getLastColumn();int firstRow = range.getFirstRow();int lastRow = range.getLastRow();if (row >= firstRow && row <= lastRow) {if (column >= firstColumn && column <= lastColumn) {return i;
                }
            }
        }return -1;
    }/** * 功能:合并单元格     */private CellRangeAddress mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        CellRangeAddress rang = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
        sheet.addMergedRegion(rang);return rang;
    }/** * 功能:设置合并单元格样式     */private void setRegionStyle(CellStyle cs, CellRangeAddress region, Sheet sheet) {for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            Row row = sheet.getRow(i);if (row == null) row = sheet.createRow(i);for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                Cell cell = row.getCell(j);if (cell == null) {
                    cell = row.createCell(j);
                    cell.setCellValue("");
                }
                cell.setCellStyle(cs);
            }
        }
    }/** * 功能:copy rows     */private void copyRows(int startRow, int endRow, int pPosition, Sheet sheet) {int pStartRow = startRow - 1;int pEndRow = endRow - 1;int targetRowFrom;int targetRowTo;int columnCount;
        CellRangeAddress region = null;int i;int j;if (pStartRow == -1 || pEndRow == -1) {return;
        }// 拷贝合并的单元格for (i = 0; i < sheet.getNumMergedRegions(); i++) {
            region = sheet.getMergedRegion(i);if ((region.getFirstRow() >= pStartRow)&& (region.getLastRow() <= pEndRow)) {
                targetRowFrom = region.getFirstRow() - pStartRow + pPosition;
                targetRowTo = region.getLastRow() - pStartRow + pPosition;
                CellRangeAddress newRegion = region.copy();
                newRegion.setFirstRow(targetRowFrom);
                newRegion.setFirstColumn(region.getFirstColumn());
                newRegion.setLastRow(targetRowTo);
                newRegion.setLastColumn(region.getLastColumn());
                sheet.addMergedRegion(newRegion);
            }
        }// 设置列宽for (i = pStartRow; i <= pEndRow; i++) {
            Row sourceRow = sheet.getRow(i);
            columnCount = sourceRow.getLastCellNum();if (sourceRow != null) {
                Row newRow = sheet.createRow(pPosition - pStartRow + i);
                newRow.setHeight(sourceRow.getHeight());for (j = 0; j < columnCount; j++) {
                    Cell templateCell = sourceRow.getCell(j);if (templateCell != null) {
                        Cell newCell = newRow.createCell(j);
                        copyCell(templateCell, newCell);
                    }
                }
            }
        }
    }/** * 功能:copy cell,不copy值     */private void copyCell(Cell srcCell, Cell distCell) {
        distCell.setCellStyle(srcCell.getCellStyle());if (srcCell.getCellComment() != null) {
            distCell.setCellComment(srcCell.getCellComment());
        }int srcCellType = srcCell.getCellType();
        distCell.setCellType(srcCellType);
    }/** * 描述:临时单元格数据     */class TempCell {private int row;private int column;private CellStyle cellStyle;private Object data;//用于列表合并,表示几列合并private int columnSize = -1;public int getColumn() {return column;
        }public void setColumn(int column) {this.column = column;
        }public int getRow() {return row;
        }public void setRow(int row) {this.row = row;
        }public CellStyle getCellStyle() {return cellStyle;
        }public void setCellStyle(CellStyle cellStyle) {this.cellStyle = cellStyle;
        }public Object getData() {return data;
        }public void setData(Object data) {this.data = data;
        }public int getColumnSize() {return columnSize;
        }public void setColumnSize(int columnSize) {this.columnSize = columnSize;
        }
    }public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
        String templateFilePath = ExcelExportUtil.class.getClassLoader().getResource("plugin/ProTiming.xlsx").getPath();
        File file = new File("/Users/sql/Downloads/test/data.xlsx");
        OutputStream os = new FileOutputStream(file);

        ExcelExportUtil excel = new ExcelExportUtil();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("B1", "03_Alpha_项目工作时间统计表");
        dataMap.put("B2", "统计时间:2017/01/01 - 2017/03/31");

        excel.writeData(templateFilePath, dataMap, 0);

        List<Map<Integer, Object>> datalist = new ArrayList<Map<Integer, Object>>();
        Map<Integer, Object> data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");

        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);

        data = new HashMap<Integer, Object>();
        data.put(1, "3/10/17");
        data.put(2, "18:50");
        data.put(3, "19:00");
        data.put(4, "李子鹏");
        data.put(5, "新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用新增项目键值对接口,供任务计时调用");
        data.put(6, "代码开发");
        data.put(7, "3.17");
        datalist.add(data);
        data = new HashMap<Integer, Object>();
        data.put(1, "");
        data.put(2, "");
        data.put(3, "");
        data.put(4, "");
        data.put(5, "");
        data.put(6, "");
        data.put(7, "");
        datalist.add(data);

        String[] heads = new String[]{"B4", "C4", "D4", "E4", "F4", "G4", "H4"};
        excel.writeDateList(templateFilePath, heads, datalist, 0);//写到输出流并移除资源        excel.writeAndClose(templateFilePath, os);

        os.flush();
        os.close();
    }

}

 

大体思路:

最主要是制作好模版

 

代码根据模版,读取设置好的列的格式,在循环数据行,读取模版中的对应的行,存在该行就取得,不存在看是否需要copy某一行,不需要就手动创建无制定格式的行,后面在为该行的每一列对应的给个单元格制定格式和数据。

 

以上是apache poi根据模板导出excel的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
平台独立性如何使企业级的Java应用程序受益?平台独立性如何使企业级的Java应用程序受益?May 03, 2025 am 12:23 AM

Java在企业级应用中被广泛使用是因为其平台独立性。1)平台独立性通过Java虚拟机(JVM)实现,使代码可在任何支持Java的平台上运行。2)它简化了跨平台部署和开发流程,提供了更大的灵活性和扩展性。3)然而,需注意性能差异和第三方库兼容性,并采用最佳实践如使用纯Java代码和跨平台测试。

考虑到平台独立性,Java在物联网(物联网)设备的开发中扮演什么角色?考虑到平台独立性,Java在物联网(物联网)设备的开发中扮演什么角色?May 03, 2025 am 12:22 AM

JavaplaysigantroleiniotduetoitsplatFormentence.1)itallowscodeTobewrittenOnCeandrunonVariousDevices.2)Java'secosystemprovidesuseusefidesusefidesulylibrariesforiot.3)

描述一个方案,您在Java中遇到了一个特定于平台的问题以及如何解决。描述一个方案,您在Java中遇到了一个特定于平台的问题以及如何解决。May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java平台独立对开发人员有什么好处?Java平台独立对开发人员有什么好处?May 03, 2025 am 12:15 AM

Java'splatFormIndenceistificantBecapeitAllowSitallowsDevelostWriTecoDeonCeandRunitonAnyPlatFormwithAjvm.this“ writeonce,runanywhere”(era)橱柜橱柜:1)交叉plat formcomplibility cross-platformcombiblesible,enablingDeploymentMentMentMentMentAcrAptAprospOspOspOssCrossDifferentoSswithOssuse; 2)

将Java用于需要在不同服务器上运行的Web应用程序的优点是什么?将Java用于需要在不同服务器上运行的Web应用程序的优点是什么?May 03, 2025 am 12:13 AM

Java适合开发跨服务器web应用。1)Java的“一次编写,到处运行”哲学使其代码可在任何支持JVM的平台上运行。2)Java拥有丰富的生态系统,包括Spring和Hibernate等工具,简化开发过程。3)Java在性能和安全性方面表现出色,提供高效的内存管理和强大的安全保障。

JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通过字节码解释、平台无关的API和动态类加载实现Java的WORA特性:1.字节码被解释为机器码,确保跨平台运行;2.标准API抽象操作系统差异;3.类在运行时动态加载,保证一致性。

Java的较新版本如何解决平台特定问题?Java的较新版本如何解决平台特定问题?May 02, 2025 am 12:18 AM

Java的最新版本通过JVM优化、标准库改进和第三方库支持有效解决平台特定问题。1)JVM优化,如Java11的ZGC提升了垃圾回收性能。2)标准库改进,如Java9的模块系统减少平台相关问题。3)第三方库提供平台优化版本,如OpenCV。

说明JVM执行的字节码验证的过程。说明JVM执行的字节码验证的过程。May 02, 2025 am 12:18 AM

JVM的字节码验证过程包括四个关键步骤:1)检查类文件格式是否符合规范,2)验证字节码指令的有效性和正确性,3)进行数据流分析确保类型安全,4)平衡验证的彻底性与性能。通过这些步骤,JVM确保只有安全、正确的字节码被执行,从而保护程序的完整性和安全性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器