iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >使用apache poi怎么实现导出excel文件
  • 836
分享到

使用apache poi怎么实现导出excel文件

apachepoiexcel 2023-05-31 13:05:23 836人浏览 八月长安
摘要

使用apache poi怎么实现导出excel文件?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。代码如下:package com.icourt.util;import org.

使用apache poi怎么实现导出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;public class ExcelExportUtil {  //模板map  private Map<String, Workbook> tempWorkbook = new HashMap<String, Workbook>();  //模板输入流map  private Map<String, InputStream> tempStream = new HashMap<String, InputStream>();    public void writeData(String templateFilePath, Map<String, Object> dataMap, int sheetNo) throws IOException, InvalidFormatException {    if (dataMap == null || dataMap.isEmpty()) {      return;    }    //读取模板    Workbook wbModule = getTempWorkbook(templateFilePath);    //数据填充的sheet    Sheet 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);  }    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);    //数据填充的sheet    Sheet wsheet = wbModule.getSheetAt(sheetNo);    //列表数据模板cell    List<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);  }    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);      }    }  }    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);          }        }      }    }  }    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();  }}

--结束END--

本文标题: 使用apache poi怎么实现导出excel文件

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

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

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

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

下载Word文档
猜你喜欢
  • 使用apache poi怎么实现导出excel文件
    使用apache poi怎么实现导出excel文件?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。代码如下:package com.icourt.util;import org....
    99+
    2023-05-31
    apachepoi excel
  • 在Java Web中Excel文件如何使用POI实现导出
    在Java Web中Excel文件如何使用POI实现导出?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。采用Spring mvc架构:Controller层代码如下@Cont...
    99+
    2023-05-31
    java web poi
  • EXCEL文件软件利用POI模板导出
    本篇文章给大家分享的是有关EXCEL文件软件利用POI模板导出,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。一般的EXCEL导出使用POI先创建一个HSSFWorkbook,然...
    99+
    2023-05-31
    poi excel
  • Java中excel文件怎么使用apache poi进行生成
    Java中excel文件怎么使用apache poi进行生成?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。首先,jarmaven 添加依赖<!-- htt...
    99+
    2023-05-31
    java apache poi excel
  • JAVA:使用POI SXSSFWorkbook方式导出Excel大数据文件
    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java对Microsoft Office格式档案读和写的功能。POI组件可以提供Java操作Microsoft Office的A...
    99+
    2023-09-01
    java excel microsoft
  • Java利用POI实现导入导出Excel表格
    本文实例为大家分享了Java利用POI实现导入导出Excel表格的具体代码,供大家参考,具体内容如下 一、Java利用POI实现导入导出Excel表格demo 1.引入依赖 <...
    99+
    2024-04-02
  • Java使用POI实现导出Excel的方法详解
    目录一、前景二、概念2.1. 简介2.2.Excel版本和相关对象2.3.WorkBook2.4.POI依赖三、POI - 写3.1.代码示例3.2. 性能对比3.3. 测试rowA...
    99+
    2022-11-13
    Java POI导出Excel Java POI Excel Java 导出Excel Java POI
  • Java使用poi导出ppt文件的实现代码
    什么是poi Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Of...
    99+
    2024-04-02
  • React怎么实现导入导出Excel文件
    这篇文章主要介绍“React怎么实现导入导出Excel文件”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“React怎么实现导入导出Excel文件”文章能帮助大家解决问题。表示层这里我是使用的是ant...
    99+
    2023-06-05
  • SpringBoot中如何使用POI导入导出Excel
    SpringBoot中如何使用POI导入导出Excel,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。1.创建Excel文档HSSFWorkbook workboo...
    99+
    2023-06-19
  • Java用POI导入导出Excel实例分析
    1、异常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException 解决方法: 使用的...
    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表格
    这篇文章主要介绍“Java如何利用POI实现导入导出Excel表格”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java如何利用POI实现导入导出Excel表格”文章能帮助大家解决问题。一、Java...
    99+
    2023-07-06
  • JavaScript实现excel文件导入导出
    目录一、需求场景描述1.此时前端上传解析excel文件可能更合适2.此时前端下载excel文件可能优雅一些二、实现思路分析1.导入excel文件实现思路分析2.导出excel文件实现...
    99+
    2024-04-02
  • Java中用POI实现将数据导出到Excel
    一、前言 数据导出为Excel在我们写项目的过程中经常用到 需要用到的jar包 poi-3.17.jar 二、具体实现步骤 //第一步创建一个webbook,对应一个Excel...
    99+
    2024-04-02
  • React实现导入导出Excel文件
    目录表示层 业务层 核心插件xlsx excel 导入 excel 导出 excel 导出插件(js-export-excel) 实现效果结语 表示层 这里我是使用的是antd的U...
    99+
    2024-04-02
  • Java使用POI导出Excel(二):多个sheet
    相关文章: Java使用POI导出Excel(一):单sheet Java使用POI导出Excel(二):多个sheet 相信在大部分的web项目中都会有导出导入Excel的需求,但...
    99+
    2024-04-02
  • 使用php 实现生成Excel文件并导出
    在现在的项目里,不管是电商项目还是别的项目,在管理端都会有导出的功能,比方说订单表导出,用户表导出,业绩表导出。这些都需要提前生成excel表,然后在导出,实际上是在代码里生成一张excel表,然后通...
    99+
    2023-09-02
    excel php 开发语言
  • JS怎么实现导出Excel和CSV文件
    这篇文章主要介绍了JS怎么实现导出Excel和CSV文件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇JS怎么实现导出Excel和CSV文件文章都会有所收获,下面我们一起来看看吧。一、js导出Excel<...
    99+
    2023-06-30
  • JavaWeb使用POI操作Excel文件实例
    1.为项目添加POIPOI官网链接点进去之后下载(上边的是编译好的类,下边的是源代码) 解压文件夹,把下面三个文件复制到WebComtent>WEB-INF>lib文件夹下再把这三个文件复制到Tomcat的lib文件夹...
    99+
    2023-05-31
    javaweb poi excel
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作