Apache POI

Apache POI 操作 Excel 表格

这里简单记录下使用 POI 向 Excel 中写入 和 从Excel 中读取内容的过程,方便后续回忆。

public class TestPoi {

    private static void write() throws Exception{
        // 在内存中创建一个 Excel 文件
        XSSFWorkbook excel = new XSSFWorkbook();
        // 在 Excel 文件中创建一个 Sheet 页
        XSSFSheet sheet = excel.createSheet("info");
        // 在 Sheet 中创建行对象, 编号从0开始
        XSSFRow row = sheet.createRow(1);
        // 创建单元格并且写入文件内容
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("年龄");

        // 创建一个新行
        row = sheet.createRow(2);
        row.createCell(1).setCellValue("冯明凯");
        row.createCell(2).setCellValue("28");
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\test.xls"));
        excel.write(fileOutputStream);
        fileOutputStream.close();
        excel.close();
    }

    private static void read() throws Exception{
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\test.xls"));
        // 读取磁盘上已经存在的 Excel 文件
        XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
        // 读取 Excel 文件中的第一个 Sheet 页
        XSSFSheet sheet = excel.getSheetAt(0);
        // 读取 Sheet 中最后一行的行号(行号从0开始计算)
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            // 获取某一行
            XSSFRow row = sheet.getRow(i);
            // 获取单元格对象
            String name = row.getCell(1).getStringCellValue();
            String age = row.getCell(2).getStringCellValue();
            System.out.println("name = " + name + " age = " + age);
        }
        // 关闭资源
        fileInputStream.close();
        excel.close();
    }
    public static void main(String[] args) throws Exception {
        write();
        read();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值