介绍

Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目,我们可以使用POI在java程序中对Miscrosoft Office各种文件进行读写操作

一般情况下,POI都是用于操作Excel文件。

Apache POI的maven坐标:

org.apache.poi

poi

org.apache.poi

poi-ooxml

Test写入测试

package com.sky.test;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**

* @author Mtz

* @version 1.0

* @2023/9/2214:33

* @function

* @comment

*/

public class POITest {

public static void write() throws Exception {

// 在内存中创建一个Excel文件

XSSFWorkbook excel = new XSSFWorkbook();

// 在Excel文件中创建一个Sheet页

XSSFSheet sheet = excel.createSheet("info");

// 在Sheet中创建行对象,rownum编号从0开始

XSSFRow row = sheet.createRow(0);

// 在创建单元格并且写入文件内容

row.createCell(1).setCellValue("城市");

row.createCell(2).setCellValue("姓名");

row = sheet.createRow(1);

row.createCell(1).setCellValue("北京");

row.createCell(2).setCellValue("张三");

row = sheet.createRow(2);

row.createCell(1).setCellValue("北京");

row.createCell(2).setCellValue("张三");

FileOutputStream out = new FileOutputStream(("D:\\info.xlsx"));

excel.write(out);

// 关闭资源

out.close();

excel.close();

}

public static void main(String[] args) throws Exception {

write();

}

}

Test读取测试

public static void read() throws Exception{

FileInputStream in = new FileInputStream("D:\\info.xlsx");

XSSFWorkbook excel = new XSSFWorkbook(in);

// 读取Excel文件中的第一个sheet页

XSSFSheet sheetAt = excel.getSheetAt(0);

// 获取Sheet中最后一行的行号

int lastRowNum = sheetAt.getLastRowNum();

for (int i = 1; i <= lastRowNum; i++) {

XSSFRow row = sheetAt.getRow(i);

String stringCellValue = row.getCell(1).getStringCellValue();

String stringCellValue2 = row.getCell(1).getStringCellValue();

System.out.println(stringCellValue+" "+stringCellValue2);

}

in.close();

excel.close();

}

相关阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。