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

说明

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

pom.xml


<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.0modelVersion>

  <groupId>com.sdutgroupId>
  <artifactId>poiDemo2artifactId>
  <version>1.0-SNAPSHOTversion>

  <name>poiDemoname>
  
  <url>http://www.example.comurl>

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

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>commons-langgroupId>
      <artifactId>commons-langartifactId>
      <version>2.6version>
    dependency>
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poiartifactId>
      <version>3.17version>
    dependency>
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-scratchpadartifactId>
      <version>3.17version>
    dependency>
    
    
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>ooxml-schemasartifactId>
      <version>1.3version>
    dependency>


    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-ooxmlartifactId>
      <version>3.17version>
    dependency>
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-excelantartifactId>
      <version>3.17version>
    dependency>
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-examplesartifactId>
      <version>3.17version>
    dependency>
    
    <dependency>
      <groupId>org.apache.xmlbeansgroupId>
      <artifactId>xmlbeansartifactId>
      <version>2.6.0version>
    dependency>
    
    <dependency>
      <groupId>com.github.virtualdgroupId>
      <artifactId>curvesapiartifactId>
      <version>1.04version>
    dependency>
  dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.0.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.7.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.20.1version>
        plugin>
        <plugin>
          <artifactId>maven-jar-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        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> params, String sheetName){
        this.insertValueToTable(wb,params,sheetName);
    }

    /**
     *  填充excel数据
     * @param wb
     * @param params
     * @param sheetName
     */
    private void insertValueToTable(Workbook wb,List> 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 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> list = new ArrayList<>();
        for (int i =0;i < 4; i++){
            Map 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);

    }
}
#目录截图

POI使用Excel模板文件循环输出行并导出Excel_第1张图片

效果截图

模板:
POI使用Excel模板文件循环输出行并导出Excel_第2张图片
结果:
POI使用Excel模板文件循环输出行并导出Excel_第3张图片

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

你可能感兴趣的:(Java)