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();
}
}
}