package com.junfun.pms.controller.excelImport;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class WordToExcelConverter {
public static void main(String[] args) {
try {
// 读取 Word 文档
FileInputStream fis = new FileInputStream("D:\\tu\\导入模板.docx");
XWPFDocument document = new XWPFDocument(OPCPackage.open(fis));
// 创建 Excel 工作簿
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
// 获取文档中的所有表格
List<XWPFTable> tables = document.getTables();
// 遍历每个表格
for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) {
XWPFTable table = tables.get(tableIndex);
// 创建新的 Excel 工作表
Sheet sheet = workbook.createSheet("Table" + (tableIndex + 1));
// 获取表格的行
List<XWPFTableRow> rows = table.getRows();
// 遍历每一行
for (int rowIndex = 0; rowIndex < rows.size(); rowIndex++) {
XWPFTableRow row = rows.get(rowIndex);
// 创建 Excel 行
Row excelRow = sheet.createRow(rowIndex);
// 获取行中的单元格
List<XWPFTableCell> cells = row.getTableCells();
// 遍历每个单元格
for (int colIndex = 0; colIndex < cells.size(); colIndex++) {
XWPFTableCell cell = cells.get(colIndex);
// 创建 Excel 单元格
Cell excelCell = excelRow.createCell(colIndex);
// 设置单元格的文本内容
excelCell.setCellValue(cell.getText());
}
}
}
// 保存 Excel 文件
FileOutputStream fos = new FileOutputStream("D:\\tu\\output.xlsx");
workbook.write(fos);
fos.close();
// 关闭 Word 文档流
fis.close();
System.out.println("Excel 文件已成功生成!");
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
throw new RuntimeException(e);
}
}
}
word文档里面的表格转成excel
最新推荐文章于 2024-08-30 17:05:27 发布