poi读写EXCEL

读写EXCEL

来源:bilibili狂神说

导入依赖

 <!--导入依赖-->
    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

写入excel

03版本

package com.kuang;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelWriteTest {

    String PATH = "F:\\";

    @Test
    public void testWrite03() throws IOException {
//        创建工作簿
        Workbook workbook = new HSSFWorkbook();
//        创建工作表
        Sheet sheet = workbook.createSheet("天气统计表");
//        创建行
        Row row1 = sheet.createRow(0);
//        创建单元格

        Cell cell11 = row1.createCell(0);
        cell11.setCellValue("今日天气");

        Cell cell12 = row1.createCell(1);
        cell12.setCellValue("今日天气2hao");

        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "天气表03版本.xls");

        workbook.write(fileOutputStream);

        fileOutputStream.close();

        System.out.println("输出文件成功!!");
    }
}

07版本更改成xlsx就行

读取

package com.kuang;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelReadTest {

    String PATH = "F:\\";

    @Test
    public void testRead03() throws IOException {

        FileInputStream inputStream = new FileInputStream(PATH + "天气表03版本.xls");
//        创建工作簿
        Workbook workbook = new HSSFWorkbook(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);
        System.out.println("读取文件成功!!");
        System.out.println(cell.getStringCellValue());
        inputStream.close();
    }
}




posted @ 2023-04-21 10:54  Dinesaw  阅读(18)  评论(0编辑  收藏  举报