Java Poi和iText是兩個非常流行的Java開源庫,并且廣泛應用于各種文檔操作。Java Poi主要用于Excel等電子表格的讀取和寫入,而iText則是一個PDF文檔的生成和編輯庫。以下是關于這兩個庫的一些介紹:
Java Poi
// 讀取Excel文件 FileInputStream fis = new FileInputStream(new File("example.xls")); HSSFWorkbook wb = new HSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); Row row = sheet.getRow(0); Cell cell = row.getCell(0); String value = cell.getStringCellValue(); // 寫入Excel文件 Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet1"); Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("Hello World"); FileOutputStream fos = new FileOutputStream(new File("example.xlsx")); wb.write(fos);
iText
// 創建PDF文檔 Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("example.pdf")); document.open(); document.add(new Paragraph("Hello World")); document.close(); // 讀取PDF文檔 PdfReader reader = new PdfReader("example.pdf"); System.out.println("Number of pages: " + reader.getNumberOfPages()); String text = PdfTextExtractor.getTextFromPage(reader, 1); // 編輯PDF文檔 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("example2.pdf")); stamper.setFormFlattening(true); stamper.close();
以上是Java Poi和iText的基本用法,它們都是非常實用的文檔操作庫。希望大家能夠在實際應用中靈活運用,提高工作效率。