java读写excel

该代码示例展示了如何使用ApachePOI库来读写Excel文件。首先添加了poi和poi-ooxml的依赖,然后创建HSSFWorkbook对象写入数据到Excel表格,数据来源于2019.txt文件。接着,程序读取excledemo.xls文件,遍历并打印所有行和列的内容。
摘要由CSDN通过智能技术生成

使用poi读写xml

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

写excel

//            如果是xlsx文件,将HSSF改为XSSF
        HSSFWorkbook hssfWorkbook=new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet();
        HSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("ID");
        row0.createCell(1).setCellValue("姓名");
        row0.createCell(2).setCellValue("课程");
        row0.createCell(3).setCellValue("分数");
        File txtFile=new File("D:\\Eclipse\\2019.txt");
        try {
            BufferedReader reader=new BufferedReader(new FileReader(txtFile));
            String textString=null;
            int num=1;
            while((textString=reader.readLine())!=null) {
                HSSFRow row = sheet.createRow(num);
                String[] split = textString.split(",");
                for (int i = 0; i < split.length; i++) {
                    row.createCell(i).setCellValue(split[i]);
                }
                num++;
            }
            FileOutputStream outputStream=new FileOutputStream(new File("D:\\Eclipse\\excledemo.xls"));
            hssfWorkbook.write(outputStream);
            reader.close();
            outputStream.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

读excel

try {
            FileInputStream excleInputStream=new FileInputStream(new File("D:\\Eclipse\\excledemo.xls"));
//            如果是xlsx文件,将HSSF改为XSSF
            HSSFWorkbook hssfWorkbook2 = new HSSFWorkbook(excleInputStream);
            HSSFSheet excleSheet = hssfWorkbook2.getSheetAt(0);
            for (int i = 0; i < excleSheet.getPhysicalNumberOfRows(); i++) {
                HSSFRow row = excleSheet.getRow(i);
                for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                    System.out.print(row.getCell(j).getStringCellValue()+" ");
                }
                System.out.println();
            }
            excleInputStream.close();
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

2019.txt

exceldemo.xls

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值