java poi读取pdf word excel文档,读取pdf文字图片

依赖

<dependency>
     	    <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
</dependency>
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
</dependency>
 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.0</version>
</dependency>
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.0</version>
</dependency>
        <!--pdf-->
<dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
</dependency>

读取pdf文本和图片

public String readPDF(String file) throws IOException {
        StringBuilder result = new StringBuilder();
        FileInputStream is = null;
        PDDocument document = null;
        is = new FileInputStream(file);
        PDFParser parser = new PDFParser(new RandomAccessBuffer(is));
        parser.parse();
        PDDocument doc = parser.getPDDocument();
        PDFTextStripper textStripper =new PDFTextStripper();
        for(int i=1;i<=doc.getNumberOfPages();i++)
        {
            textStripper.setStartPage(i);
            textStripper.setEndPage(i);
            textStripper.setSortByPosition(true);//按顺序行读
            String s=textStripper.getText(doc);
            result.append(s);
        }
//        //文本为空,读图片提取图片里的文字,
//        if(result.toString().trim().length()==0){
//            for(int i=1;i<doc.getNumberOfPages();i++){
//                PDPage page=doc.getPage(i-1);
//                PDResources resources = page.getResources();
//                Iterable<COSName> xobjects =resources.getXObjectNames();
//                if(xobjects!=null) {
//                    Iterator<COSName> imageIter = xobjects.iterator();
//                    while (imageIter.hasNext()) {
//                        COSName cosName = imageIter.next();
//                        boolean isImageXObject = resources.isImageXObject(cosName);
//                        if (isImageXObject) {
//                            //获取每页资源的图片
//                            PDImageXObject ixt = (PDImageXObject) resources.getXObject(cosName);
//                            File outputfile = new File("D:\\tmp\\" + cosName.getName() + ".jpg");
//                            ImageIO.write(ixt.getImage(), "jpg", outputfile);//可保存图片到本地
//							 //调用图片识别文字接口
//							//...
//                        }
//                    }
//                }
//            }
//        }
        doc.close();
        return result.toString();
    }

简单读取word docx/doc文字

public static String readDoc(String path) throws IOException, XmlException, OpenXML4JException {
        String resullt = "";
        InputStream is =null;
        if (path.toLowerCase().endsWith(".doc")) {
            is=new FileInputStream(new File(path));
            WordExtractor re = new WordExtractor(is);
            resullt = re.getText();
            re.close();
        } else if (path.toLowerCase().endsWith(".docx")) {
            OPCPackage opcPackage = POIXMLDocument.openPackage(path);
            POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
            resullt = extractor.getText();
            extractor.close();
        }
        return resullt;
    }
    
//针对doc文件另一种写法
public void readWords() throws Exception{
        String file="C:\\xx.doc";
        HWPFDocument document=new HWPFDocument(new FileInputStream(file));
        Range r=document.getRange();
        for(int i=0;i<r.numParagraphs();i++){
            Paragraph paragraph = r.getParagraph(i);
            System.out.println(paragraph.text());
        }
    }

读取word doc表格内容

public void read() throws Exception{
       String file="C:\\xx.doc";
       HWPFDocument document=new HWPFDocument(new FileInputStream(file));
       Range r=document.getRange();
        TableIterator tableIterator=new TableIterator(r);
        while (tableIterator.hasNext()){
            Table table=tableIterator.next();
            int numRows = table.numRows();
            for(int j=0;j<numRows;j++){
                TableRow row = table.getRow(j);
                for (int k=0;k<row.numCells();k++){
                    TableCell cell = row.getCell(k);
                    System.out.println(j+" "+k+" "+cell.text());//行号+列号+文字内容
                }
                System.out.println("\n");
            }
        }
   }

读取word doc图片

public void readPicture() throws Exception{
        String file="C:\\xx.doc";
        HWPFDocument document=new HWPFDocument(new FileInputStream(file));
        Range r=document.getRange();
        PicturesTable picturesTable=document.getPicturesTable();
        List<Picture> pictureList=picturesTable.getAllPictures();//一次性获取,如果想按段落依次可以写进map
        Map<Integer, Picture> lookup =new HashMap<Integer, Picture>();
        for (Picture p : pictureList) {
            lookup.put(p.getStartOffset(), p);
        }
        System.out.println(pictureList.size());
        for(int i=0;i<r.numParagraphs();i++){
            Paragraph paragraph = r.getParagraph(i);
            for(int j=0;j<paragraph.numCharacterRuns();j++){
                if(picturesTable.hasPicture(paragraph.getCharacterRun(j))){
                    System.out.println("有图片");
                    Picture picture=lookup.get(paragraph.getCharacterRun(j));//依次从map取图片
                    picture.writeImageContent(new FileOutputStream("  "));
                }
            }
        }
    }

读取excel

针对xlsx文件 XSSFWorkbook
针对xls文件 HSSFWorkbook

public static String readEXCELxlsx(String file) throws IOException {
        StringBuilder content = new StringBuilder();
        XSSFWorkbook workbook = new XSSFWorkbook(file);//根据文件类型选择xlsx
        for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
            if (null != workbook.getSheetAt(numSheets)) {
                XSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
                for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {
                    if (null != aSheet.getRow(rowNumOfSheet)) {
                        XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
                        for (short cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) {
                            if (null != aRow.getCell(cellNumOfRow)) {
                                XSSFCell aCell = aRow.getCell(cellNumOfRow);// 获得列值
                                if (convertCell(aCell).length() > 0) {
                                    content.append(convertCell(aCell));
                                }
                            }
                            content.append("\n");
                        }
                    }
                }
            }
        }
        return  content.toString();
 }

格式化单元格内容

private static String convertCell(Cell cell) {
        NumberFormat formater = NumberFormat.getInstance();
        formater.setGroupingUsed(false);
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        if(cell.getCellType()== CellType.NUMERIC){
            //cellValue = formater.format(cell.getNumericCellValue());
            //解决读取日期数字混有中文问题如2021/8/9读出中文
            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                Date theDate = cell.getDateCellValue();
                SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cellValue = dff.format(theDate);
            }else{
                DecimalFormat df = new DecimalFormat("0");
                cellValue = df.format(cell.getNumericCellValue());
            }
        }
        else if(cell.getCellType()==CellType.STRING){
            cellValue = cell.getStringCellValue();
        }
        else if(cell.getCellType()==CellType.BLANK){
            cellValue = cell.getStringCellValue();
        }
        else if(cell.getCellType()==CellType.BOOLEAN){
            cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString();
        }
        else if(cell.getCellType()==CellType.ERROR){
            cellValue = String.valueOf(cell.getErrorCellValue());
        }
        return (cellValue.trim());
    }

输出到excel

public void exportToExcel() throws Exception{
        List<Student> studentList=new ArrayList<>();
        studentList.add(new Student().setName("张三").setAge(12).setDate(new Date()));
        studentList.add(new Student().setName("李四").setAge(12).setDate(new Date()));
        studentList.add(new Student().setName("王五").setAge(12).setDate(new Date()));
        XSSFWorkbook xssfWorkbook=new XSSFWorkbook();
        XSSFSheet sheet=xssfWorkbook.createSheet("第一个表单");
        XSSFRow rowTitle = sheet.createRow(0);
        rowTitle.createCell(0).setCellValue("姓名");
        rowTitle.createCell(1).setCellValue("年龄");
        rowTitle.createCell(2).setCellValue("时间");
        for (int i=0;i<studentList.size();i++){
            XSSFRow valueRow=sheet.createRow(i+1);
            valueRow.createCell(0).setCellValue(studentList.get(i).getName());
            valueRow.createCell(1).setCellValue(studentList.get(i).getAge());
            valueRow.createCell(2).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(studentList.get(i).getDate()));
        }
        XSSFSheet sheet2=xssfWorkbook.createSheet("第二个表单");
        XSSFRow rowTitle2 = sheet2.createRow(0);
        rowTitle2.createCell(0).setCellValue("姓名");
        rowTitle2.createCell(1).setCellValue("年龄");
        rowTitle2.createCell(2).setCellValue("时间");
        for (int i=0;i<studentList.size();i++){
            XSSFRow valueRow=sheet2.createRow(i+1);
            valueRow.createCell(0).setCellValue(studentList.get(i).getName());
            valueRow.createCell(1).setCellValue(studentList.get(i).getAge());
            valueRow.createCell(2).setCellValue(studentList.get(i).getDate());
        }
        File file=new File("D:\\tmp","student.xlsx");
        xssfWorkbook.write(new FileOutputStream(file));
        xssfWorkbook.close();
    }

office转pdf

https://blog.csdn.net/UnicornRe/article/details/119677482?spm=1001.2014.3001.5501

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 要获取 PDF 文件、Word 文件、Excel 文件等文件的页数,您可以使用 Apache POI 库。 Apache POI 是一个开源的 Java 库,可用于读写 Microsoft Office 文件格式,包括 WordExcel、PowerPoint 等。 下面是示例代码,该代码使用 Apache POI 读取 Word 文件,并获取文件的页数: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import java.io.FileInputStream; import java.io.IOException; public class WordPageCount { public static void main(String[] args) throws IOException { // 读取文件 FileInputStream fis = new FileInputStream("example.docx"); XWPFDocument document = new XWPFDocument(fis); // 获取页数 int pageCount = 0; for (XWPFParagraph p : document.getParagraphs()) { String text = p.getText(); if (text.contains("page")) { pageCount++; } } System.out.println("Page count: " + pageCount); } } ``` 对于 PDF 文件,您可以使用 Apache PDFBox 库获取页数。下面是示例代码: ```java import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File; public class PDFPageCount { public static void main(String[] args) throws IOException { // 读取文件 File file = new File("example.pdf"); PDDocument document = PDDocument.load(file); // 获取页数 int pageCount = document.getNumberOfPages(); System.out.println("Page count: " + pageCount); } } ``` 对于 Excel 文件,您可以使用下面的代码获取工作簿的页数(即工作表的数量): ```java import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; public class ExcelPageCount { ### 回答2: 要获取PDF文件、Word文件、Excel文件等文件的页数,可以使用Java中的不同库和API来实现。 1. 获取PDF文件的页数: 使用开源的PDFBox库可以很方便地获取PDF文件的页数。首先,需要添加PDFBox库的依赖项,如Maven中的依赖项: ```xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.15</version> </dependency> ``` 然后,使用以下代码获取PDF文件的页数: ```java import org.apache.pdfbox.pdmodel.PDDocument; // 打开PDF文件 PDDocument document = PDDocument.load(new File("file.pdf")); // 获取页数 int totalPages = document.getNumberOfPages(); // 关闭PDF文件 document.close(); ``` 2. 获取Word文件的页数: 使用Apache POI库可以读取Word文件,并获取其页数。首先,需要添加Apache POI库的依赖项,如Maven中的依赖项: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> ``` ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> ``` 然后,使用以下代码获取Word文件的页数: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; // 打开Word文件 XWPFDocument document = new XWPFDocument(new FileInputStream("file.docx")); // 获取页数 int totalPages = document.getProperties().getExtendedProperties().getUnderlyingProperties().getPages(); // 关闭Word文件 document.close(); ``` 3. 获取Excel文件的页数: 使用Apache POI库也可以读取Excel文件,并获取其页数。依然需要添加Apache POI库的依赖项。然后,使用以下代码获取Excel文件的页数: ```java import org.apache.poi.ss.usermodel.WorkbookFactory; // 打开Excel文件 Workbook workbook = WorkbookFactory.create(new FileInputStream("file.xlsx")); // 获取页数 int totalPages = workbook.getNumberOfSheets(); // 关闭Excel文件 workbook.close(); ``` 以上是在Java中获取PDF文件、Word文件和Excel文件的页数的方法。根据对应的文件类型,选择合适的库或API,并通过相应的方法获取页数即可。 ### 回答3: 要使用Java获取不同文件类型(如PDFWordExcel等)的页数,可以使用以下方法: 1. 对于PDF文件,可以使用Apache PDFBox库。该库提供了一个PDF文档类,可以获取文档的总页数。以下是一个示例代码: ```java import org.apache.pdfbox.pdmodel.PDDocument; public class PDFPageCount { public static int getPageCount(String pdfFilePath) { int pageCount = 0; try (PDDocument document = PDDocument.load(new File(pdfFilePath))) { pageCount = document.getNumberOfPages(); } catch (IOException e) { e.printStackTrace(); } return pageCount; } public static void main(String[] args) { String pdfFilePath = "path/to/pdf/file.pdf"; int pageCount = getPageCount(pdfFilePath); System.out.println("PDF文件总页数:" + pageCount); } } ``` 2. 对于Word文件,可以使用Apache POI库。POI库提供了HSSFWorkbook和XSSFWorkbook类,分别用于处理旧版(.xls)和新版(.xlsx)的Excel文件。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; public class WordPageCount { public static int getPageCount(String wordFilePath) { int pageCount = 0; try (XWPFDocument document = new XWPFDocument(new FileInputStream(wordFilePath))) { pageCount = document.getProperties().getExtendedProperties().getUnderlyingProperties().getPages(); } catch (IOException e) { e.printStackTrace(); } return pageCount; } public static void main(String[] args) { String wordFilePath = "path/to/word/file.docx"; int pageCount = getPageCount(wordFilePath); System.out.println("Word文件总页数:" + pageCount); } } ``` 3. 对于Excel文件,可以使用Apache POI库。POI库提供了HSSFWorkbook和XSSFWorkbook类,分别用于处理旧版(.xls)和新版(.xlsx)的Excel文件。以下是一个示例代码: ```java import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelPageCount { public static int getPageCount(String excelFilePath) { int pageCount = 0; try (Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath))) { pageCount = workbook.getNumberOfSheets(); } catch (IOException e) { e.printStackTrace(); } return pageCount; } public static void main(String[] args) { String excelFilePath = "path/to/excel/file.xlsx"; int pageCount = getPageCount(excelFilePath); System.out.println("Excel文件总页数:" + pageCount); } } ``` 以上是使用Java获取不同类型文件的页数的方法。需要注意的是,需要提前引入相关的库(如PDFBox和POI库)以及处理异常情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可——叹——落叶飘零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值