# Apache POI 教學 ### 簡介 &nbsp;&nbsp;是一個基於Java的免費開源函式庫,相較於JasperReports只能匯出,Apache POI可以讓我們讀取、匯出Excel、Word、Power Point等Microsoft Office的各種文件。 官網來源:https://poi.apache.org/ --- ### 加入依賴 Apache POI Maven網址: https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad pom.xml ``` XML= <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.5.0</version> </dependency> ``` --- ### EXCEL教學 #### 建立Excel檔案 ``` Java= Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("姓名"); row.createCell(1).setCellValue("年齡"); try (FileOutputStream fos = new FileOutputStream("example.xlsx")) { workbook.write(fos); } workbook.close(); ``` #### 讀取Excel檔案 ``` Java= try (FileInputStream fis = new FileInputStream("example.xlsx")) { Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { System.out.print(cell.toString() + "\t"); } System.out.println(); } } ``` --- ### WORD教學 #### 建立Word檔案 ``` Java= XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("Hello Apache POI"); run.setBold(true); try (FileOutputStream out = new FileOutputStream("example.docx")) { document.write(out); } document.close(); ``` #### 建立Word表格 ``` Java= XWPFTable table = document.createTable(3, 3); table.getRow(0).getCell(0).setText("方案名稱"); table.getRow(0).getCell(1).setText("期間"); table.getRow(0).getCell(2).setText("金額"); table.getRow(1).getCell(0).setText("方案A"); table.getRow(1).getCell(1).setText("2025/01/01~2025/12/31"); table.getRow(1).getCell(2).setText("1000"); ``` --- ### 總結 &nbsp;&nbsp;以上就是簡易的Apache POI使用教學文章。 --- > 歡迎隨意引用或拷貝,若有涉及侵權概不負責。