package com.example.demo.Utils;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Excel导入导出工具类
*/
public class ExcelUtils {
/**
* 从Excel文件读取数据
*
* @param filePath 文件路径
* @return 读取的数据列表
*/
public static List<List<String>> readFromExcel(String filePath) {
List<List<String>> data = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
List<String> rowData = new ArrayList<>();
for (Cell cell : row) {
String cellValue = "";
if (cell.getCellType() == CellType.STRING) {
cellValue = cell.getStringCellValue();
} else if (cell.getCellType() == CellType.NUMERIC) {
cellValue = String.valueOf(cell.getNumericCellValue());
}
rowData.add(cellValue);
}
data.add(rowData);
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
/**
* 将数据写入Excel文件
*
* @param filePath 文件路径
* @param data 数据列表
*/
public static void writeToExcel(String filePath, List<List<String>> data) {
try (Workbook workbook = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream(filePath)) {
Sheet sheet = workbook.createSheet();
for (int i = 0; i < data.size(); i++) {
Row row = sheet.createRow(i);
List<String> rowData = data.get(i);
for (int j = 0; j < rowData.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowData.get(j));
}
}
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String filePath = "data.xlsx";
// 从Excel文件读取数据
List<List<String>> data = ExcelUtils.readFromExcel(filePath);
for (List<String> rowData : data) {
for (String cellData : rowData) {
System.out.print(cellData + "\t");
}
System.out.println();
}
// 将数据写入Excel文件
List<List<String>> newData = new ArrayList<>();
newData.add(Arrays.asList("Name", "Age", "City"));
newData.add(Arrays.asList("Alice", "25", "New York"));
newData.add(Arrays.asList("Bob", "30", "London"));
newData.add(Arrays.asList("Charlie", "35", "Tokyo"));
ExcelUtils.writeToExcel("newData.xlsx", newData);
}
}
java中Excel导入导出工具类
最新推荐文章于 2024-04-29 15:03:34 发布