你可以使用Apache POI库来处理Word和Excel文件。在Spring Boot应用中,你可以使用POI来读取Word中的表格内容,然后创建一个新的Excel文件并将表格内容写入其中。
引入依赖
首先,你需要在你的Spring Boot项目中添加Apache POI的依赖。在你的pom.xml文件中添加以下依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.1</version>
</dependency>
创建转换服务
接下来,创建一个Spring Boot的服务类来实现Word转Excel的功能:
@Service
public class WordToExcelService {
public void convertWordToExcel(String wordFilePath, String excelFilePath) throws IOException, InvalidFormatException {
FileInputStream fis = new FileInputStream(wordFilePath);
XWPFDocument document = new XWPFDocument(fis);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
int rowNum = 0;
for (XWPFTable table : document.getTables()) {
for (int i = 0; i < table.getRows().size(); i++) {
Row row = sheet.createRow(rowNum++);
for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
String cellValue = table.getRow(i).getCell(j).getText();
Cell cell = row.createCell(j);
cell.setCellValue(cellValue);
}
}
}
FileOutputStream fos = new FileOutputStream(excelFilePath);
workbook.write(fos);
fis.close();
fos.close();
workbook.close();
document.close();
}
}
编写Controller类
然后,创建一个Controller类来接收请求,并调用WordToExcelService来执行Word转Excel的操作。
@RestController
public class WordToExcelController {
@Autowired
private WordToExcelService wordToExcelService;
@PostMapping("/convert")
public ResponseEntity<String> convertWordToExcel(@RequestParam("wordFilePath") String wordFilePath,
@RequestParam("excelFilePath") String excelFilePath) {
try {
wordToExcelService.convertWordToExcel(wordFilePath, excelFilePath);
return ResponseEntity.ok("Word转Excel转换成功!");
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("转换失败:" + e.getMessage());
}
}
}
总结
到这里,启动项目,发送一个POST请求到/convert路径,同时提供Word文件的路径wordFilePath和Excel文件的路径excelFilePath时,它将会执行Word转Excel的操作。可以在Spring Boot应用中调用这个接口来实现你的需求。当然在实际使用的场景中,需要注意适当处理异常情况,比如文件路径错误、文件不存在等。来保证你的程序的健壮性。