1 导包:
 
<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.1</version>
    </dependency>
    
    <!-- 要使用 XSSFWorkbook 时导入 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.1</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.2</version>
    </dependency>
</dependencies>
 
2 读取Excel
 
2.1 将文档读取为Java对象
 
FileInputStream fileInputStream = new FileInputStream("/Users/apple/Develop/workspace/test/poi-read/src/main/resources/target.xlsx");
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
 
2.2 读取Sheet
 
XSSFSheet sheet = xssfWorkbook.getSheet("prducts");
 
2.3 读取行(Row)
 
int rowNums = sheet.getLastRowNum();
XSSFRow row = sheet.getRow(0)
 
2.4 读取单元格/列(Cell)
 
short cellNum = row.getLastCellNum();
XSSFCell cell = row.getCell((short) 0);
double value = cell.getNumericCellValue()
 
2.5 关闭文件引用
 
xssfWorkbook.close();
 
3 创建Excel
 
3.1 创建Excel对象
 
XSSFWorkbook workbook = new XSSFWorkbook();
 
3.2 创建Sheet
 
XSSFSheet userAgeLte3Sheet = workbook.createSheet("products");
 
3.3 创建行(Row)
 
XSSFRow row = sheet.createRow(0);
 
3.4 创建单元格/列(Cell)
 
XSSFCell cell = row.createCell(0);
 
3.5 向单元格中写入数据
 
cell.setCellValue("ID");
 
3.6 写入到本地文件
 
String path = "/Users/apple/Desktop/test/target.xlsx";
FileOutputStream fileOutputStream = new FileOutputStream(path);
workbook.write(fileOutputStream);
workbook.close();
fileOutputStream.close();