美文网首页Java
POI(Java操作Excel文件):封装写工具类

POI(Java操作Excel文件):封装写工具类

作者: 掌灬纹 | 来源:发表于2021-02-25 09:37 被阅读0次

    apache的POI是常用的Java开发excel应用的第三方工具

    POI常用对象分析

    • Workbook - 工作簿
    • Sheet - 工作表 文件下的分页
    • Row - 行对象
    • Col - 列对象
      (Row,Col) 行列索引 锁定唯一操作单元格


      对象对照解析

    maven依赖

        <!--导入依赖-->
        <dependencies>
            <!--03 版本 -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>4.1.2</version>
            </dependency>
    
            <!--07版本-->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>4.1.2</version>
            </dependency>
    
            <!--日期格式化工具-->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>2.10.1</version>
            </dependency>
    
            <!--测试-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.1</version>
            </dependency>
    
        </dependencies>
    

    复杂分表写excel测试

       @Test
        public void testWrite07() throws Exception {
            // 1.创建工作簿
            Workbook workbook = new XSSFWorkbook();
            // 2.创建sheet
            Sheet userSheet = workbook.createSheet("用户角色表");
            Sheet roleSheet = workbook.createSheet("用户权限表");
    
            // 第一行
            Row userRow1 = userSheet.createRow(0);
            userRow1.createCell(0).setCellValue("账号");
            userRow1.createCell(1).setCellValue("用户名");
            userRow1.createCell(2).setCellValue("角色类别");
            userRow1.createCell(3).setCellValue("操作时间");
    
            // 测试数据 10 行
            for (int i = 1; i < 11; i++){
                Row row = userSheet.createRow(i);
                row.createCell(0).setCellValue("root" + i);
                row.createCell(1).setCellValue("测试用户" + i);
                row.createCell(2).setCellValue((int)(Math.random()*5 + 1));
                row.createCell(3).setCellValue(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
            }
    
            // 用户权限
            Row roleRow1 = roleSheet.createRow(0);
            roleRow1.createCell(0).setCellValue("权限类别");
            roleRow1.createCell(1).setCellValue("权限名称");
    
            for (int i = 1; i < 6 ; i++){
                Row row = roleSheet.createRow(i);
                row.createCell(0).setCellValue(i);
                row.createCell(1).setCellValue("测试权限" + i);
            }
    
            FileOutputStream fileOutputStream = new FileOutputStream(path + "//excel//用户权限表07.xlsx");
            // 生成文件
            workbook.write(fileOutputStream);
    
            fileOutputStream.close();
            System.out.println("文件生成成功");
    
        }
    

    封装写工具类

    • 封装三种工作簿用于写文件不同场景调用
    1. HSSF 03版本文件写 (最多 65535行)
    2. XSSF 07版本文件写 无上限
    3. SXSSF 提升大文件excel写速度
    • 提取文件名、表名、行列内容、路径、起始行为参数封装写工具类
    package com.ht.utils;
    
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.streaming.SXSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.List;
    
    /**
     *
     * @author 掌灬纹
     * @since 2021-2-25
     */
    public class PoiWriteUtils {
    
        /**
         *
         * 1. 文件名 自动添加后缀 .xls
         * 2. sheetName 分页命名
         * 3. rowBeginIndex 起始行索引 哪行开始存储 0-第一行
         * 4. excel 行标题名称
         * 5. excel 列存放内容
         * 6. 文件生成路径
         */
    
        /**
         * 03版本 xls 文件写
         * @param fileName      文件名
         * @param sheetName     分页命名
         * @param rowBeginIndex 起始行索引 0-第一行
         * @param row           行标题内容
         * @param col           列存放内容
         * @param path          文件生成路径
         * @return true&false
         * @throws IOException
         */
        public boolean writeExcelByPoiHSSF(
                String fileName, String sheetName,
                int rowBeginIndex, List<String> row,
                List<List<Object>> col,
                String path
        ) throws IOException {
    
            // 处理文件后缀名 即 路径
            fileName += ".xls";
            path += fileName;
    
            // 创建表格
            Workbook workbook = new HSSFWorkbook();
            Sheet sheet = workbook.createSheet(sheetName);
            // 起始行
            Row row1 = sheet.createRow(rowBeginIndex);
            int rowLen = row.size();
            for (int i = 0; i < rowLen; i++) {
                // 第一行 第几列 初始化
                row1.createCell(i).setCellValue(row.get(i));
            }
    
            // 文件内容
            // 内容记录 行数
            int colLen = col.size();
            for (int i = rowBeginIndex + 1; i < colLen + rowBeginIndex + 1; i++) {
                // 多少行内容
                Row temp = sheet.createRow(i);
                for (int j = 0; j < col.get(i - rowBeginIndex - 1).size(); j++) {
                    // 每行内容写入文件
                    temp.createCell(j).setCellValue(col.get(i - rowBeginIndex - 1).get(j).toString());
                }
            }
    
            // IO操作
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(path);
                workbook.write(out);// 写文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                out.close();
                workbook.close();
            }
            return true;
        }
    
    
        /**
         * 07 版本 xlsx 文件写
         * @param fileName
         * @param sheetName
         * @param rowBeginIndex
         * @param row
         * @param col
         * @param path
         * @return
         * @throws IOException
         */
        public boolean writeExcelByPoiXHSSF(
                String fileName, String sheetName,
                int rowBeginIndex, List<String> row,
                List<List<Object>> col,
                String path
        ) throws IOException{
            // 处理文件后缀名 即 路径
            fileName += ".xlsx";
            path += fileName;
    
            // 创建表格
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet(sheetName);
            // 起始行
            Row row1 = sheet.createRow(rowBeginIndex);
            int rowLen = row.size();
            for (int i = 0; i < rowLen; i++) {
                // 第一行 第几列 初始化
                row1.createCell(i).setCellValue(row.get(i));
            }
    
            // 文件内容
            // 内容记录 行数
            int colLen = col.size();
            for (int i = rowBeginIndex + 1; i < colLen + rowBeginIndex + 1; i++) {
                // 多少行内容
                Row temp = sheet.createRow(i);
                for (int j = 0; j < col.get(i - rowBeginIndex - 1).size(); j++) {
                    // 每行内容写入文件
                    temp.createCell(j).setCellValue(col.get(i - rowBeginIndex - 1).get(j).toString());
                }
            }
    
            // IO操作
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(path);
                workbook.write(out);// 写文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                out.close();
                workbook.close();
            }
            return true;
    
        }
    
        /**
         * 大数据写 快速写重构
         * @param fileName
         * @param sheetName
         * @param rowBeginIndex
         * @param row
         * @param col
         * @param path
         * @return
         */
        public boolean writeExcelByPoiSXSSFBigData(
                String fileName, String sheetName,
                int rowBeginIndex, List<String> row,
                List<List<Object>> col,
                String path
        ) throws IOException{
            // 处理文件后缀名 即 路径
            fileName += ".xlsx";
            path += fileName;
    
            // 创建表格
            Workbook workbook = new SXSSFWorkbook();
            Sheet sheet = workbook.createSheet(sheetName);
            // 起始行
            Row row1 = sheet.createRow(rowBeginIndex);
            int rowLen = row.size();
            for (int i = 0; i < rowLen; i++) {
                // 第一行 第几列 初始化
                row1.createCell(i).setCellValue(row.get(i));
            }
    
            // 文件内容
            // 内容记录 行数
            int colLen = col.size();
            for (int i = rowBeginIndex + 1; i < colLen + rowBeginIndex + 1; i++) {
                // 多少行内容
                Row temp = sheet.createRow(i);
                for (int j = 0; j < col.get(i - rowBeginIndex - 1).size(); j++) {
                    // 每行内容写入文件
                    temp.createCell(j).setCellValue(col.get(i - rowBeginIndex - 1).get(j).toString());
                }
            }
    
            // IO操作
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(path);
                workbook.write(out);// 写文件
                //清空临时文件
                ((SXSSFWorkbook)workbook).dispose();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                out.close();
                workbook.close();
            }
            return true;
        }
    }
    
    

    工具类测试

    package com.ht;
    
    import com.ht.utils.PoiWriteUtils;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    // 测试工具
    public class TestUtils {
    
        public static void main(String[] args) throws IOException {
            PoiWriteUtils utils = new PoiWriteUtils();
    
            // 数据库字段
            List<String> row = new ArrayList<String>();
            row.add("姓名");
            row.add("年龄");
            row.add("家庭住址");
    
            // 数据库内容
            List<List<Object>> col = new ArrayList();
            List<Object> col1 = new ArrayList<Object>();
            col1.add("Ht");col1.add("20");col1.add("河北省廊坊市");
            List<Object> col2 = new ArrayList<Object>();
            col2.add("爱神");col2.add("18");col2.add("河北省唐山市");
            col.add(col1);col.add(col2);
    
            // 路径
            String path = "E:\\enviroment\\git\\cupid-study\\poi-easyexcel\\poi\\excel\\";
    
            utils.writeExcelByPoiHSSF("测试", "测试表", 0,row,col,path);
        }
    
        @Test
        public void testBigData() throws IOException {
            PoiWriteUtils utils = new PoiWriteUtils();
            // 大数据 写入
            List<String> row = new ArrayList<String>();
            row.add("姓名");
            row.add("年龄");
            row.add("家庭住址");
    
            // 文件内容 按集合存记录
            List<List<Object>> col = new ArrayList();
            for (int i = 0; i < 100000; i++){
                List<Object> temp = new ArrayList<Object>();
                temp.add("测试姓名" + i + 1);temp.add(i + 1);temp.add("测试地址" + i + 1);
                col.add(temp);
            }
    
            String path = "E:\\enviroment\\git\\cupid-study\\poi-easyexcel\\poi\\excel\\";
            utils.writeExcelByPoiSXSSFBigData("大数据测试","大数据测试",0,row,col,path);
            System.out.println("文件生成成功!");
        }
    }
    
    10w行数据测试

    相关文章

      网友评论

        本文标题:POI(Java操作Excel文件):封装写工具类

        本文链接:https://www.haomeiwen.com/subject/jvdyfltx.html