POI使用Excel模板文件循环输出行并导出Excel

说明

上一篇POI使用word模板文件循环输出行并导出word已经写了导出word,这里就写导出excel

pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sdut</groupId>
  <artifactId>poiDemo2</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>poiDemo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
    <!--<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.17</version>
    </dependency>-->
    <!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>ooxml-schemas</artifactId>
      <version>1.3</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-excelant</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-examples</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
    <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.6.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.github.virtuald/curvesapi -->
    <dependency>
      <groupId>com.github.virtuald</groupId>
      <artifactId>curvesapi</artifactId>
      <version>1.04</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
ExcelReporter.class
package com.sdut.PoiDemo2;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import javax.sound.midi.Soundbank;
import java.io.*;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by lzx on 2018/8/12
 */

public class ExcelReporter {

    // 模板路径
    private String fileLoaclPath = null;
    // 输入流
    private InputStream  inputStream = null;
    // 输入流
    private FileOutputStream outputStream = null;
    // 表格对象
    private Workbook wb = null;

    public ExcelReporter(){

    }
    public ExcelReporter(String fileLoaclPath){
        this.fileLoaclPath = fileLoaclPath;
    }

    public void setFileLoaclPath(String fileLoaclPath) {
        this.fileLoaclPath = fileLoaclPath;
    }

    /**
     *  初始化
     * @throws IOException
     */
    public void init() throws IOException {
        //inputStream =  ExcelReporter.class.getResourceAsStream("/model/" + this.fileLoaclPath);
        inputStream = new FileInputStream(new File(this.fileLoaclPath));
        if (this.fileLoaclPath.endsWith(".xlsx")){
            wb = new XSSFWorkbook(inputStream);
        }else if(this.fileLoaclPath.endsWith(".xls")){
            wb = new HSSFWorkbook(inputStream);
        }else
            throw new RuntimeException("model file format is not valid , this : " + this.fileLoaclPath + " , eg:.xlsx or xls");
    }

    /**
     *  导出excel表格
     * @param params
     * @param sheetName
     */
    public void export(List<Map<String,String>> params, String sheetName){
        this.insertValueToTable(wb,params,sheetName);
    }

    /**
     *  填充excel数据
     * @param wb
     * @param params
     * @param sheetName
     */
    private void insertValueToTable(Workbook wb,List<Map<String,String>> params,String sheetName) {
        // 获取模板中的sheet
        Sheet sheet = wb.getSheetAt(0);
        // 设置模板页的名称
        wb.setSheetName(0, sheetName);
        // 获得模板航
        Row tmpRow = sheet.getRow(1);
        // 获得非空白的行数
        int last = sheet.getLastRowNum();
        // 循环遍历填充数据
        for (int i = 0, len = params.size(); i < len; i++){
            // 获的开始填充的一行 就是模板的下一行
            int index = i+last+1;
            Map<String,String> map = params.get(i);
            // 创建新的一行
            Row row = sheet.getRow(index);
            if(row == null) {
                row = sheet.createRow(index);
            }
            // 循环便利模板行的列 获取${key}中的key
            for (int j = tmpRow.getFirstCellNum() ; j < tmpRow.getLastCellNum() ; j++){
                // 得到模板行的第j列单元格
                Cell tmpCell = tmpRow.getCell(j);
                // 获取key
                String key = tmpCell.getStringCellValue().replace("$", "").replace("{", "").replace("}", "");
                int columnindex = tmpCell.getColumnIndex();
                System.out.println(MessageFormat.format("这是第{0}行,第{1}列的key:{2}",index,columnindex,key));
                // 得到创建的一行的第j列单元格
                Cell c = row.getCell(j);
                if(c == null)
                    c = row.createCell(columnindex);
                // 填充单元格数据
                c.setCellValue(map.get(key));
            }
        }
        // 删除模板行
        sheet.shiftRows(2,5,-1);

    }
    /**
     *  收尾方法
     * @param outDocPath
     * @return
     * @throws IOException
     */
    public boolean generate(String outDocPath) throws IOException{
        outputStream = new FileOutputStream(new File(outDocPath));
        wb.write(outputStream);
        this.close(wb);
        this.close(inputStream);
        this.close(outputStream);
        return true;
    }

    /**
     *  关闭Workbook
     * @param wb
     */
    private void close(Workbook wb) {
        if (wb != null) {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *  关闭输入流
     * @param is
     */
    private void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  关闭输出流
     * @param os
     */
    private void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
ExcelExportDemo.class
package com.sdut.PoiDemo2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lzx on 2018/8/12
 */

public class ExcelExportDemo {
    public static void main(String[] args) throws IOException {
        // 添加假数据 这里你也可以从数据库里获取数据
        List<Map<String, String>> list = new ArrayList<>();
        for (int i =0;i < 4; i++){
            Map<String,String> map = new HashMap<>();
            map.put("id", i+"");
            map.put("name", "我在这"+i);
            map.put("car", "你好"+i);
            map.put("shop", "加班啊"+i);
            map.put("content", "123");
            list.add(map);
        }
        // 模板文件输入输出地址
        String filePath = "E:/workspace/poiDemo2/src/main/java/config/demo.xlsx";
        String outPath = "E:/workspace/poiDemo2/src/main/java/config/demo1.xlsx";
        // 开始导出
        ExcelReporter excelReporter = new ExcelReporter();
        excelReporter.setFileLoaclPath(filePath);
        excelReporter.init();
        excelReporter.export(list,"20180814");
        excelReporter.generate(outPath);

    }
}
#目录截图

这里写图片描述

效果截图

模板:
这里写图片描述
结果:
这里写图片描述

源码地址:https://download.csdn.net/download/sdut406/10604271
参考博客:https://blog.csdn.net/QQ317968200/article/details/79739183

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值