美文网首页
使用 java apache poi 操作 excel xlsx

使用 java apache poi 操作 excel xlsx

作者: 云中小鱼 | 来源:发表于2020-11-18 11:12 被阅读0次

工作中临时需要对各种订单量进行简单的统计分析,为了方便简单学习了apache poi 对 xlsx 文件的基本操作,简单记录

1. 引包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2. 创建文件

    public static void main(String[] args) {
        // 创建文件,创建工作薄
        File xlsFile = new File("C:/demo/demo.xlsx");
        xlsFile.getParentFile().mkdirs();
        try (FileOutputStream outputStream = new FileOutputStream(xlsFile);
             XSSFWorkbook xssWorkbook = new XSSFWorkbook()) {
            // 创建单元格样式
            XSSFCellStyle cellStyle = xssWorkbook.createCellStyle();
            // 内容居中
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            // 创建工作表
            XSSFSheet sheet = xssWorkbook.createSheet("sheet1");
            for (int i = 0; i < 10; i++) {
                // 设置工作表宽度(宽度单位为1/256个字符宽度)
                sheet.setColumnWidth(i, 20 * 256);
                // 创建行(创建行不一定需要从0开始)
                XSSFRow row = sheet.createRow(i);
                for (int j = 0; j < 5; j++) {
                    // 创建单元格,(创建单元格也不需要从0开始)
                    XSSFCell cell = row.createCell(j);
                    // 给单元格设置内容
                    cell.setCellValue("row->" + i + ", column->" + j);
                    // 给单元格设置样式
                    cell.setCellStyle(cellStyle);
                }
            }
            // 输出
            xssWorkbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3. 读取文件

    public static void main(String[] args) {
        // 读取文件获取工作薄
        File excelFile = new File("C:/demo/demo.xlsx");
        try (FileInputStream inputStream = new FileInputStream(excelFile);
             XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream)) {
            // 获取工作表数量
            int numberOfSheets = xssfWorkbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                // 获取工作表
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                // 获取最后一条行数(包含该行)
                int lastRowNum = sheet.getLastRowNum();
                for (int j = 0; j <= lastRowNum; j++) {
                    // 获取行
                    XSSFRow row = sheet.getRow(j);
                    // 获取单元格列数(不包含该行)
                    short lastCellNum = row.getLastCellNum();
                    for (int k = 0; k < lastCellNum; k++) {
                        // 获取单元格
                        XSSFCell cell = row.getCell(k);
                        // 以String的格式获取单元格内容
                        System.out.println(cell.getStringCellValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

相关文章

网友评论

      本文标题:使用 java apache poi 操作 excel xlsx

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