所需要的依赖
<!--读取excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
工具类
package com.cs.cs_demo.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.cs.cs_demo.service.UserService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
public class ExcelUtils {
public static void readExcel(String fileName) throws IOException {
// 创建文件输入流 fileName 列如:D:\\文档\\xxxx.xlsx
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
// 创建工作簿对象
Workbook workbook = WorkbookFactory.create(fileInputStream);
// 获取第一个工作表
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:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
case FORMULA:
System.out.print(cell.getCellFormula() + "\t");
break;
case BLANK:
System.out.print("\t");
break;
default:
System.out.print("\t");
}
}
System.out.println();
}
// 关闭文件输入流
fileInputStream.close();
}
public static void writeExcel(String fileName) throws IOException {
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建行和单元格
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello, World!");
// 设置单元格样式
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
cell.setCellStyle(style);
// 导出 Excel 文件
FileOutputStream fileOut = new FileOutputStream(fileName);
workbook.write(fileOut);
fileOut.close();
}
}