import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.WorkbookFactory; import com.deepoove.poi.XWPFTemplate; import java.io.*; import java.util.ArrayList; import java.util.HashMap; public class Application { static final String PATH = "output/"; static File templateWord = new File(Application.class.getClassLoader().getResource("template.docx").getFile()); static File listExcel = new File(Application.class.getClassLoader().getResource("list.xlsx").getFile()); static ArrayList<CustomData> list = new ArrayList<>(); // 人員列表,可自定義 CustomData public static void main(String[] args) throws IOException, InvalidFormatException { list = getExcelList(listExcel); output(templateWord, list); } /** * 取得人員名單 */ static ArrayList<CustomData> getExcelList(File excel) throws IOException, InvalidFormatException { Sheet sheet = WorkbookFactory.create(excel).getSheetAt(0); for (int row = 0; row < sheet.getLastRowNum() + 1; row++) { // get data Row r = sheet.getRow(row); if(r.getCell(0)!= null){ String index = String.format("%03.0f", Float.parseFloat(r.getCell(0).toString().trim())); String name = r.getCell(1).toString().trim(); list.add(new CustomData(index, name,"out"+index+".docx")); } } return list; } /** * 輸出檔案 */ static void output(File word, ArrayList<CustomData> list) { File dir = new File(PATH); if(dir.exists()){ dir.delete(); } dir.mkdir(); list.stream().forEach((data) -> { try { XWPFTemplate outputFile = XWPFTemplate.compile(word) .render(new HashMap<String, Object>() {{ put("index", data.index); put("name", data.name); }}); FileOutputStream os = new FileOutputStream(PATH +data.filename); outputFile.write(os); os.flush(); os.close(); outputFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }); } }