你可以使用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應用中調用這個接口來實現你的需求。當然在實際使用的場景中,需要注意適當處理異常情況,比如文件路徑錯誤、文件不存在等。來保證你的程序的健壯性。