本範例示範如何使用 Apache POI 庫讀取 .xls 格式的 Excel 檔案,從指定工作表中提取檔案路徑清單,再根據這些路徑將編譯後的 .class 檔案(含內部類別)從來源目錄複製到部署目錄。程式碼採用命令列參數傳入 Excel 目錄、來源類別目錄、目標部署目錄以及 Web 內容根目錄(預設 WebContent),適合自動化部署流程。
.xls 檔,讀取指定工作表,從第 5 行開始逐行取得第 2 欄(索引 1)的字串值,組成檔案路徑清單回傳。.java 替換為 .class,並根據路徑前綴(src/ 或 Web 內容目錄)轉換為 WEB-INF/classes/ 或相對路徑,呼叫 copyFile 執行實際複製,同時處理內部類別檔(如 ClassName$1.class)。// 讀取 Excel 並取得路徑清單
public List<String> getDatasInSheet(int sheetNumber, File dir) throws FileNotFoundException, IOException {
List<String> result = new ArrayList<>();
File[] files = dir.listFiles();
for (File f : files) {
if (!f.getName().toLowerCase().endsWith(".xls")) continue;
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(f));
HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
int rowCount = sheet.getLastRowNum();
for (int rowIndex = 4; rowIndex <= rowCount; rowIndex++) {
HSSFRow row = sheet.getRow(rowIndex);
if (row != null) {
HSSFCell cell = row.getCell(1);
String str = (String) getCellString(cell);
if (str != null && str.length() > 1) result.add(str);
}
}
}
return result;
}
// 複製單一檔案(含建立目錄)
private boolean copyFile(String str, String sourcePath, String destPath) throws IOException {
File sourceFile = new File(sourcePath + str);
if (!sourceFile.exists()) return false;
File destFile = new File(destPath + str);
File destDir = new File(destFile.getParent());
if (!destDir.exists()) destDir.mkdirs();
try (InputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len);
return true;
}
}
java DeployByExcel <Excel目錄> <來源類別目錄> <部署目標目錄> [WebContent目錄名]
範例:
java DeployByExcel /tmp/excel /project/build/classes /deploy/target WebContent
.xls (HSSF),若需 .xlsx 請改用 XSSFWorkbook。src/ 為 WEB-INF/classes/。$1.class、$2.class…)會自動嘗試複製,直到找不到為止。log4j.properties。