apache poi 的使用

       apache poi 是用来处理office各种文件格式的开源项目,简单来说就是可以对office中各种文件进行读写操作(一般用于操作excel文件)

使用步骤:

  1.引入maven坐标poi 和poi-ooxml

 poi使用实例:

通过poi创建excel文件并写入文件内容

public class POITest{
    
       public static void write() throw Exception{

        //在内存中创建一个excel表
        XXFSWorkbook excel = new  XXSWorkbook();
        //在excel中创建sheet页
        XXFSWorkbook sheet = excel.createSheet("info");
        //在sheet页中创建行对象,编号从0开始
        XXSFRow row = sheet.createRow(0);
        //创建单元格写入内容
        row.createCell(0).setCellValue("姓名")
        row.createCeel(1).setCellValue("城市")
        XXSFRow row = sheet.createRow(1);
        //创建单元格写入内容
        row.createCell(0).setCellValue("张三")
        row.createCeel(1).setCellValue("北京")
        
        //通过输出流将内存中的内容写入磁盘中 
        FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"))
        excel.write(out);
        
        //关闭流
        out.close;
        excel.close;


       }


}

poi读取文件中内容

public class ExcelReader {
    public static void main(String[] args) {
        // 指定要读取的 Excel 文件路径
        String filePath = "/yourPath/readexample.xlsx"; 
        readExcel(filePath);
    }

    public static void readExcel(String filePath) {
        try (FileInputStream inputStream = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(inputStream)) { 
            // 获取第一个工作表(也可以通过工作表名称获取特定的工作表)
            Sheet sheet = workbook.getSheetAt(0); 
            // 遍历工作表中的行
            for (Row row : sheet) {
                // 遍历行中的单元格
                for (Cell cell : row) {
                    // 根据单元格的数据类型获取相应的值
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) { 
                                System.out.print(cell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
                            System.out.print(" " + "\t");
                    }
                }
                System.out.println(); 
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值