apache POI 使用

依赖



    org.apache.poi
    poi
    4.0.0



    org.apache.poi
    poi-ooxml
    4.0.0

HSSFWorkBook:操作2003版本以前的(包括2003版本),扩展名.xls,该类在org.apache.poi:poi中

XSSFWorkBook:操作2007版本以后的(包括2007版本),拓展名.xlsx,该类在org.apache.poi:poi-ooxml中

SXSSFWorkBook:对于海量的数据进行操作

对于不同版本的EXCEL文档要使用不同的工具类,如果使用错了,会提示如下错误信息。

org.apache.poi.openxml4j.exceptions.InvalidOperationException

org.apache.poi.poifs.filesystem.OfficeXmlFileException

读取Excel

public static void main(String[] args) {
    File file = new File("D://dd.xlsx");
    try {
        Workbook workbook = null;
        InputStream inputStream = new FileInputStream(file);
        if (file.getName().endsWith("xls")) {
            //Excel 2003
            workbook = new HSSFWorkbook(inputStream);
        } else if (file.getName().endsWith("xlsx")) {
            // Excel 2007/2010
            workbook = new XSSFWorkbook(inputStream);
        }
        inputStream.close();
        //工作表对象
        Sheet sheet = workbook.getSheetAt(0);
        //总行数
        int rowLength = sheet.getLastRowNum() + 1;
        //工作表的列
        Row row = sheet.getRow(0);
        //总列数
        int colLength = row.getLastCellNum();
        //得到指定的单元格
        Cell cell = row.getCell(0);
        //得到单元格样式
        CellStyle cellStyle = cell.getCellStyle();
        System.out.println("行数:" + rowLength + ",列数:" + colLength);
        for (int i = 0; i < rowLength; i++) {
            row = sheet.getRow(i);
            for (int j = 0; j < colLength; j++) {
                cell = row.getCell(j);
                //Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串时就有可能报异常:
                //Cannot get a STRING value from a NUMERIC cell
                //将所有的需要读的Cell表格设置为String格式
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                } else {
                    // 没有cell将创建一个
                    cell = row.createCell(1, CellType.STRING);
                }
                //对Excel进行修改
                if (i > 0 && j == 1) {
                    cell.setCellValue(String.valueOf(new Random().nextInt(10)));
                }
                System.out.print(cell.getStringCellValue() + "\t");
            }
            System.out.println();
        }

        //将修改好的数据保存
        OutputStream outputStream = new FileOutputStream(file);
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

设置单元格类型

row.getCell(0).setCellType(CellType.STRING);
row.getCell(1).setCellType(CellType.NUMERIC);

生成并导出Excel

/**
 * 创建并下载excel
 *
 * @param headName 表头
 * @param list     数据字符串集合
 * @param expName  文件名
 * @param dir      文件路径
 */
private void createAndDownloadExcel(HttpServletResponse response, String[] headName, List> list, String expName, String dir) throws UnsupportedEncodingException {
    // --- Excel 生成 ---
    // 格式化时间
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Sheet1");
    // 创建表头
    HSSFRow row = sheet.createRow(0);
    HSSFCell cell;
    // 循环表头信息
    for (int y = 0; y < headName.length; y++) {
        cell = row.createCell((short) y);
        cell.setCellValue(headName[y]);
    }
    // 循环数据信息
    for (int x = 0; x < list.size(); x++) {
        row = sheet.createRow(x + 1);
        List rowString = list.get(x);
        for (int i = 0; i < rowString.size(); i++) {
            cell = row.createCell((short) i);
            cell.setCellValue(rowString.get(i));
        }
    }
    // 生成excel文件
    Path excelPath = Paths.get(dir + "/" + expName + ".xls");
    if (Files.notExists(excelPath)) {
        try {
            Files.createFile(excelPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 写入excel文件
    File file = excelPath.toFile();
    try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
        workbook.write(fileOutputStream);
    } catch (IOException ignored) {
    }

    // --- 下载设置 ---
    // 设置下载文件
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("gbk"), StandardCharsets.ISO_8859_1));
    response.addHeader("Content-Length", "" + file.length());

    // 写入输出流并写出
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);

        outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        // 使内存中的数据立刻写出
        outputStream.flush();
    } catch (Exception e) {
        log.error("excel导出异常", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ignored) {
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ignored) {
            }
        }
    }

    // 生成Excel删除
    try {
        Files.deleteIfExists(excelPath);
    } catch (IOException ignored) {
    }
}

页面直接

window.location.href = "xxx";

你可能感兴趣的:(Java)