New file |
| | |
| | | package com.zt.life.util; |
| | | |
| | | import com.aspose.pdf.*; |
| | | import org.apache.poi.xssf.usermodel.XSSFSheet; |
| | | import org.apache.poi.xssf.usermodel.XSSFWorkbook; |
| | | |
| | | import java.io.FileInputStream; |
| | | import java.io.IOException; |
| | | |
| | | public class test { |
| | | |
| | | static String path = "d:\\源文件\\"; |
| | | |
| | | public static void main(String[] args) { |
| | | try { |
| | | //创建工作簿对象 |
| | | XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(path + "配置.xlsx")); |
| | | //获取工作簿下sheet的个数 |
| | | int sheetNum = xssfWorkbook.getNumberOfSheets(); |
| | | //遍历工作簿中的所有数据 |
| | | for (int i = 0; i < sheetNum; i++) { |
| | | //读取第i个工作表 |
| | | System.out.println("读取第" + (i + 1) + "个sheet"); |
| | | XSSFSheet sheet = xssfWorkbook.getSheetAt(i); |
| | | //获取最后一行的num,即总行数。此处从0开始 |
| | | int maxRow = sheet.getLastRowNum(); |
| | | if (sheet.getRow(1) != null && sheet.getRow(1).getCell(0) != null) { |
| | | String srcPath = sheet.getRow(1).getCell(0).toString(); |
| | | String targetPath = sheet.getRow(1).getCell(1).toString(); |
| | | Document pdfDoc = new Document(srcPath); |
| | | for (int row = 1; row <= maxRow; row++) { |
| | | //获取最后单元格num,即总单元格数 ***注意:此处从1开始计数*** |
| | | // 源文件路径 |
| | | String srcPath2 = sheet.getRow(row).getCell(0).toString(); |
| | | String beforePath = sheet.getRow(row - 1).getCell(0).toString(); |
| | | String nextPath = null; |
| | | if (sheet.getRow(row + 1) != null && sheet.getRow(row + 1).getCell(0) != null) { |
| | | nextPath = sheet.getRow(row + 1).getCell(0).toString(); |
| | | } |
| | | |
| | | |
| | | if (!beforePath.equals(srcPath2) && row - 1 != 0) { |
| | | // 输入文件路径 |
| | | targetPath = sheet.getRow(row).getCell(1).toString(); |
| | | pdfDoc = new Document(srcPath2); |
| | | } |
| | | |
| | | String srcText = sheet.getRow(row).getCell(2).toString(); |
| | | String targetText = sheet.getRow(row).getCell(3).toString(); |
| | | String fontName = sheet.getRow(row).getCell(4).toString(); |
| | | |
| | | TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(srcText); |
| | | PageCollection pages = pdfDoc.getPages(); |
| | | pages.accept(textFragmentAbsorber); |
| | | if (srcText.equals("1300.89")){ |
| | | System.out.println(111); |
| | | } |
| | | for (TextFragment textFragment : textFragmentAbsorber.getTextFragments()) { |
| | | textFragment.setText(targetText); |
| | | textFragment.getTextState().setFont(FontRepository.findFont(fontName)); |
| | | } |
| | | if (!srcPath2.equals(nextPath)) { |
| | | pdfDoc.save(targetPath); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |