Excel文件工具

方法:

  • 输出数据到自定义模板的Excel输出流
  • 从 Excel文件获取 Workbook 对象
  • 把 Workbook对象内容输出到 Excel文件
  • 把 Workbook对象输出到 Excel输出流
  • 输出数据到 Workbook对象中指定页码
  • 读取 Excel文件第一页(参数为文件的路径)
  • 读取 Excel文件第一页(参数为文件名称)
  • 读取xls格式Excel文件第一页
  • 读取xlsx格式Excel文件第一页
  • 读取Workbook第一页
  • 读取指定页面的Excel
  • 解析单元格中的值
  • 设置单元

示例代码:

1、Excel工具类

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

import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Excel 工具类(兼容xls和xlsx)
 */
public class ExcelUtils {

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
    private static final DateFormat FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    /**
     * 输出数据到自定义模板的Excel输出流
     * @param excelTemplate 自定义模板文件
     * @param data 数据
     * @param outputStream 输出流
     */
    public static void writeDataToTemplateOutputStream(File excelTemplate, List<List<Object>> data, OutputStream outputStream) throws IOException {
        Workbook book = ExcelUtils.getWorkbookFromExcel(excelTemplate);
        ExcelUtils.writeDataToWorkbook(null,data,book,0);
        ExcelUtils.writeWorkbookToOutputStream(book,outputStream);
    }

    /**
     * 从 Excel文件获取 Workbook 对象
     * @param excelFile  excel文件
     * @return Workbook 对象
     * @throws IOException 文件类型错误异常
     */
    private static Workbook getWorkbookFromExcel(File excelFile) throws IOException {

        try (
                InputStream inputStream = new FileInputStream(excelFile);
        ) {
            // 如果excel文件是以xls结尾的
            if (excelFile.getName().endsWith(XLS)) {
                return new HSSFWorkbook(inputStream);
            }
            // 如果excel文件是以xlsx结尾的
            else if (excelFile.getName().endsWith(XLSX)) {
                return new XSSFWorkbook(inputStream);
            } else {
                throw new IOException("文件类型错误");
            }
        }
    }

    /**
     * 把 Workbook对象内容输出到 Excel文件
     * @param book  Workbook对象
     * @param file Excel文件
     * @throws IOException
     */
    public static void writeWorkbookFile(Workbook book, File file) throws IOException {

        //判断文件是否存在,如果不存在
        if (!file.exists()) {
            //判断父级文件是否存在,如果不存在则创建文件夹
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //创建新的文件
            file.createNewFile();
        }
        OutputStream outputStream = new FileOutputStream(file);
        writeWorkbookToOutputStream(book,outputStream);
    }

    /**
     * 把 Workbook对象输出到 Excel输出流
     * @param book Workbook对象
     * @param outputStream Excel输出流
     * @throws IOException
     */
    private static void writeWorkbookToOutputStream(Workbook book, OutputStream outputStream) throws IOException {

        book.write(outputStream);
    }

    /**
     * 输出数据到 Workbook对象中指定页码
     * @param title 标题写在第一行,可传null
     * @param data 数据
     * @param book Workbook对象
     * @param page 输出数据到 Workbook 指定页码的页面数
     */
    private static void writeDataToWorkbook(List<String> title, List<List<Object>> data, Workbook book, int page) {

        Sheet sheet = book.getSheetAt(page);
        Row row = null;  //
        Cell cell = null;   // 工作表

        /**
         * 设置表头
         */
        // 如果抬头不为空
        if (null != title && !title.isEmpty()) {
            row = sheet.getRow(0);      //得到第一行
            //如果行为空,则创建行
            if (null == row) {
                row = sheet.createRow(0);
            }

            for (int i = 0; i < title.size(); i++) {
                // 获取每行的单元格
                cell = row.getCell(i);
                if (cell == cell) {
                    cell = row.createCell(i);
                }
                cell.setCellValue(title.get(i));
            }
        }

        //每行的数据
        List<Object> rowData = null;
        for (int i = 0; i < data.size(); i++) {
            row = sheet.getRow(i + 1);
            //如果没有行
            if (null == row) {
                //新建行
                row = sheet.createRow(i + 1);
            }
            rowData = data.get(i);
            //如果改行数据为空则继续下一行
            if (null == rowData) {
                continue;
            }
            for (int j = 0; j < rowData.size(); j++) {
                cell = row.getCell(j);
                if (null == cell) {
                    cell = row.createCell(j);
                }
                setValue(cell,rowData.get(j));
            }
        }
    }

    /**
     * 读取 Excel文件第一页
     * @param pathname 文件路径
     * @return 第一页数据集合
     * @throws IOException  错误时抛出异常,由调用者处理
     */
    public static List<List<Object>> readExcelFirstSheet(String pathname) throws IOException{
        File file = new File(pathname);
        return readExcelFirstSheet(file);
    }

    /**
     * 读取 Excel 文件第一页
     * @param file Excel文件
     * @return 第一页数据集合
     * @throws IOException 错误时抛出异常,由调用者处理
     */
    public static List<List<Object>> readExcelFirstSheet(File file) throws IOException {

        try (
                InputStream inputStream = new FileInputStream(file);
        ) {

            if (file.getName().endsWith(XLS)) {
                return readXlsFirstSheet(inputStream);
            } else if (file.getName().endsWith(XLSX)) {
                return readXlsxFirstSheet(inputStream);
            } else {
                throw new IOException("文件类型错误");
            }
        }
    }

    /**
     * 读取xls格式Excel文件第一页
     * @param inputStream Excel文件输入流
     * @return 第一页数据集合
     * @throws IOException 错误时抛出异常,由调用者处理
     */
    private static List<List<Object>> readXlsFirstSheet(InputStream inputStream) throws IOException {
        Workbook workbook = new HSSFWorkbook(inputStream);
        return readExcelFirstSheet(workbook);
    }

    /**
     * 读取xlsx格式Excel文件第一页
     * @param inputStream Excel文件输入流
     * @return 第一页数据集合
     * @throws IOException 错误时抛出异常,由调用者处理
     */
    private static List<List<Object>> readXlsxFirstSheet(InputStream inputStream) throws IOException {
        Workbook workbook = new XSSFWorkbook(inputStream);
        return readExcelFirstSheet(workbook);
    }

    /**
     * 读取Workbook第一页
     * @param book Workbook对象
     * @return 第一页数据集合
     */
    public static List<List<Object>> readExcelFirstSheet(Workbook book) {
        return readExcel(book,0);
    }

    /**
     * 读取指定页面的Excel
     * @param book Workbook对象
     * @param page 页码
     * @return 指定页面数据集合
     */
    private static List<List<Object>> readExcel(Workbook book, int page) {
        List<List<Object>> list = new ArrayList<>();
        Sheet sheet = book.getSheetAt(page);
        for (int i = 0; i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);

            //如果当前行为空,则加入空,保持行号一致
            if (null == row) {
                list.add(null);
                continue;
            }

            List<Object> columns = new ArrayList<>();
            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                columns.add(getValue(cell));
            }

            list.add(columns);
        }

        return list;
    }

    /**
     * 解析单元格中的值
     *
     * @param cell 单元格
     * @return 单元格内的值
     */
    private static Object getValue(Cell cell) {
        if (null == cell) {
            return null;
        }
        Object value = null;
        switch (cell.getCellType()) {
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;

            case NUMERIC:

                // 日期类型,转换为日期
                if (DateUtil.isCellDateFormatted(cell)) {
                    value = cell.getDateCellValue();
                }

                // 数值类型
                else {

                    // 默认返回double,创建BigDecimal返回准确值
                    value = new BigDecimal(cell.getNumericCellValue());
                }
                break;

            default:
                value = cell.toString();
                break;
        }

        return value;
    }

    /**
     * 设置单元
     * @param cell
     * @param value
     */
    private static void setValue(Cell cell, Object value) {
        // 如果没有工作表
        if (null == cell) {
            return;
        }
        // 单元格为空
        if (null == value) {
            cell.setCellValue((String) null);
        }

        else if (value instanceof Date) {
            cell.setCellValue(FORMAT.format((Date) value ));
        }

        else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        }
        else {
            cell.setCellValue(value.toString());
        }
    }

}

2、测试代码

import java.io.IOException;
import java.util.List;

public class ExcelUtilsTest {
    public static void main(String[] args) throws IOException {

        // 测试,读取excel文件
        String filePath = "C:\Users\***\Desktop\test.xlsx";
        List<List<Object>> lists = ExcelUtils.readExcelFirstSheet(filePath);
        for (List<Object> object:lists) {
            System.out.println(object);
        }
    }
}
原文地址:https://www.cnblogs.com/nastu/p/15269366.html