poi处理Excel

文章介绍了使用ApachePOI库在Java中进行Excel数据的导出和导入操作,包括创建工作簿、设置表头、写入数据以及读取数据的过程。示例代码展示了如何将列表转换为Excel文件并提供数据格式化处理。
package com.cyao.util.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * poi处理Excel
 *
 * @author ChangYao
 */
public class PoiExcel {
    private static final int maxRowCount = 65000;// 不能够超过Excel的最大容量

    private PoiExcel() {

    }

    /**
     * 导出数据到Excel 一个Excel页的最大行数为65536
     *
     * @param datas    目标数据
     * @param titles   标题数组
     * @param function Function实现类
     * @param pathname 文件路径
     * @param <T>      目标类型
     */
    public static <T> void doExport(List<T> datas, String[] titles, Function<T, String[]> function, String pathname) {
        try {
            doExport(datas, titles, function, new FileOutputStream(pathname));
        } catch (Exception ignored) {

        }
    }

    /**
     * 导出数据到Excel 一个Excel页的最大行数为65536
     *
     * @param datas    目标数据
     * @param titles   标题数组
     * @param function Function实现类
     * @param os       输出流
     * @param <T>      目标类型
     */
    public static <T> void doExport(List<T> datas, String[] titles, Function<T, String[]> function, OutputStream os) {
        Workbook workBook = new HSSFWorkbook();
        int pageCount = (datas.size() + maxRowCount - 1) / maxRowCount;
        for (int i = 0; i < pageCount; i++) {
            workBook.createSheet("Sheet" + i);
        }
        for (int page = 0; page < pageCount; page++) {
            Sheet sheet = workBook.getSheetAt(page);
            Row titleRow = sheet.createRow(0);
            for (int i = 0; i < titles.length; i++) {
                titleRow.createCell(i).setCellValue(titles[i]);
            }
            int end = page == pageCount - 1 ? datas.size() : (page + 1) * maxRowCount;
            for (int i = page * maxRowCount; i < end; i++) {
                Row dataRow = sheet.createRow(i + 1 - page * maxRowCount);
                T t = datas.get(i);
                String[] values = function.apply(t);
                for (int j = 0; j < values.length; j++) {
                    //dataRow.createCell(j).setCellValue(values[j]);
                    String value = values[j];
                    if (titles[j].contains("金额") && value.matches("\\d+(.\\d+)?")) {
                        dataRow.createCell(j).setCellValue(Double.parseDouble(value));
                    } else {
                        dataRow.createCell(j).setCellValue(value);
                    }
                }
            }
        }
        try {
            workBook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入Excel数据到文件
     *
     * @param pathname    文件路径
     * @param rowConsumer
     */
    public static void doImport(String pathname, Consumer<FileRow> rowConsumer) {
        try {
            doImport(new FileInputStream(pathname), rowConsumer);
        } catch (IOException ignored) {

        }
    }

    /**
     * 导入Excel数据
     *
     * @param inputStream 输入流
     * @param rowConsumer
     */
    public static void doImport(InputStream inputStream, Consumer<FileRow> rowConsumer) {
        Workbook wb = null;
        try {
            wb = WorkbookFactory.create(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        assert wb != null;
        Sheet sheet = wb.getSheetAt(0);
        int totalRows = sheet.getPhysicalNumberOfRows();
        DataFormatter formatter = new DataFormatter();//正确获取String的方式
        for (int i = 1; i < totalRows; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            FileRow fr = new FileRow(i);
            int totalCells = row.getPhysicalNumberOfCells();
            for (int j = 0; j < totalCells; j++) {
                Cell cell = row.getCell(j);
                fr.addCol(j, formatter.formatCellValue(cell));
            }
            rowConsumer.accept(fr);
        }
    }

    public static class FileRow {
        private List<String> data = new ArrayList<>(26);
        private int row;

        public FileRow(int row) {
            this.row = row;
        }

        public int getRow() {
            return row;
        }

        public void addCol(int colIndex, String value) {
            this.data.add(colIndex, value);
        }

        public String getCol(int colIndex) {
            return this.data.get(colIndex);
        }
    }
}
            List<Map<String, String>> datas = new ArrayList<>();

            for (int i = 0; i < 5; i++) {
                Map<String, String> map = new HashMap<>();
                map.put("id", new DecimalFormat("H0000").format(i + 1L));
                map.put("name", new DecimalFormat("Name0000").format(i + 1L));
                map.put("age", String.valueOf(RandomUtils.nextInt(18, 33)));
                datas.add(map);
            }

            String[] titles = new String[]{"编号", "姓名", "年龄"};

            String pathname = "d://test.xls";

            PoiExcel.doExport(datas, titles, t -> new String[]{t.get("id"), t.get("name"), t.get("age")}, pathname);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漠星曜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值