POI自己有些东西不是很熟悉。记录一下。
POI读取
cpp
public static void main(String[] args) throws Exception {
// 读取文件
String filePath = "D:\\12.xlsx"; // 替换为你的 Excel 文件路径
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(fis)) {
// 遍历所有工作表
for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
Sheet sheet = workbook.getSheetAt(sheetIndex);
System.out.println("工作表名称: " + sheet.getSheetName());
// 遍历所有行
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = getCellValue(cell);
System.out.println(cellValue);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getCellValue(Cell cell) {
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return DateFormatUtils.format(cell.getDateCellValue(), "yyyy-MM-dd HH:mm:ss");
} else {
return NumberToTextConverter.toText(cell.getNumericCellValue()).trim();
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case FORMULA:
return cell.getCellFormula();
case ERROR:
return ErrorEval.getText(cell.getErrorCellValue());
default:
return "";
}
}
}
POI写入
cpp
public static void main(String[] args) throws Exception {
// 1. 创建一个新的工作簿(Excel文件)
Workbook workbook = new XSSFWorkbook();
// 2. 创建一个工作表(Sheet)
Sheet sheet = workbook.createSheet("学生信息表");
// 3. 模拟数据
String[][] data = {
{"姓名", "年龄", "成绩"},
{"张三", "20", "90"},
{"李四", "21", "85"},
{"王五", "19", "95"}
};
// 4. 写入数据
int rowNum = 0;
for (String[] rowData : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(colNum++);
cell.setCellValue(cellData);
}
}
// 5. 自动调整列宽
for (int i = 0; i < data[0].length; i++) {
sheet.autoSizeColumn(i);
}
// 6. 写入到文件
try (FileOutputStream outputStream = new FileOutputStream("D:\\13.xlsx")) {
workbook.write(outputStream);
System.out.println("Excel 文件写入成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 7. 关闭工作簿,释放资源
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}