欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Poi-1:个人记录使用过程的问题

程序员文章站 2024-02-10 14:30:46
...

个人在poi的使用过程中遇到的问题
最近公司需要使用java开发文件浏览的程序,整体使用的是Java Swing做视图,文件部分需要展示PPT,Word以及Excel,所以需要把他们进行转换成一定格式,通过查询注意到使用Poi可以操作这几个文件类型,于是决定使用Poi。

Apache poi下载网址

http://poi.apache.org/download.html

PPT的转换

使用poi很容易做到,只是注意ppt和pptx的转换,通过查询相关方法很容易做到。我主要是通过poi将两种格式转化为图片,然后在Swing的Canva上进行展示。

//ppt转换图片:
public static boolean doPPTtoImage(String URL) {
        FileInputStream FileInputStream = null;
        FileOutputStream FileOutStream = null;        HSLFSlideShow oneHSLFSlideShow = null;
        //图片放大尺寸
        int times=1;
        long t1;
        // 创建图片保存路径
        String path = new GetFromFilePath().getNameFromPath(URL);
        boolean flag = new DirSet().mkDir("./" + path);        try {
            try {
                FileInputStream = new FileInputStream(URL);
                oneHSLFSlideShow = new HSLFSlideShow(FileInputStream);
            } catch (FileNotFoundException e) {
                logger.error("ppt文件不存在==",e);
                return false;
            }
            catch (IOException e) {
                logger.error("读取文件异常==",e);
                return false;
            }            // 获取PPT每页的大小
            Dimension pgsize = oneHSLFSlideShow.getPageSize();
            // 所有的PPT转为播放片
            List<HSLFSlide> slides = oneHSLFSlideShow.getSlides();
            // 对每一张幻灯片进行转换和操作            logger.debug("共"+slides.size()+"页");
            t1=System.currentTimeMillis();
            for (int i = 0; i < slides.size(); i++) {
                List<List<HSLFTextParagraph>> oneTextParagraphs = slides.get(i).getTextParagraphs();
                for (List<HSLFTextParagraph> list : oneTextParagraphs) {
                    for (HSLFTextParagraph hslfTextParagraph : list) {
                        List<HSLFTextRun> HSLFTextRunList = hslfTextParagraph.getTextRuns();
                        for (int j = 0; j < HSLFTextRunList.size(); j++) {
                            // 设置字体大小
                            Double size = HSLFTextRunList.get(j).getFontSize();
                            if ((size <= 0) || (size >= 26040)) {
                                HSLFTextRunList.get(j).setFontSize(20.0);
                            }
                            // 设置字体样式为宋体,解决乱码
                            HSLFTextRunList.get(j).setFontFamily("宋体");
                        }
                    }
                }
                // BufferedImage对象
                BufferedImage img = new BufferedImage(pgsize.width *times ,pgsize.height * times,
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.scale(times, times);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width * times, pgsize.height * times));
                slides.get(i).draw(graphics);                // 设置图片的存放路径和图片格式
                String imgName = new GetFromFilePath().getNameFromPath(URL) + "_" + (i + 1) + ".jpeg";
                try {
                    FileOutStream = new FileOutputStream(
                            "./" + path +"/"+ new GetFromFilePath().getNameFromPath(URL) + "_" + (i + 1) + ".jpeg");
                } catch (FileNotFoundException e) {
                    logger.error(""+e);
                    e.printStackTrace();
                }
                // 图片保存指定目录
                try {
                    ImageIO.write(img, "jpeg", FileOutStream);
                } catch (IOException e) {
                    logger.error("保存ppt-image图片error"+e);
                    return false;
                }
            }
            logger.debug("总耗时:"+(System.currentTimeMillis()-t1)+"ms");
        } finally {
            try {
                if (FileInputStream != null) {
                    FileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (FileOutStream != null) {
                    FileOutStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    //pptx转换图片
    public  boolean doPPTXtoImage(String URL) {
        FileInputStream is = null ;        //图片放大尺寸
        int times=4;
        
        long t1 = System.currentTimeMillis();
        String path="./"+new GetFromFilePath().getNameFromPath(URL);
        boolean flag= new DirSet().mkDir(path);        try {
            is = new FileInputStream(URL);
            XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
            is.close();
            // 获取大小
            Dimension pgsize = xmlSlideShow.getPageSize();
            // 获取幻灯片
            List<XSLFSlide> slides = xmlSlideShow.getSlides();            logger.debug("pptx文件共:"+slides.size()+"页");
            t1=System.currentTimeMillis();
            for (int i = 0 ; i < slides.size() ; i++) {
                List<XSLFShape> shapes = slides.get(i).getShapes();
                for (XSLFShape shape : shapes) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape sh = (XSLFTextShape) shape;
                        List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                        for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                            List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                            for (XSLFTextRun xslfTextRun : textRuns) {
                                xslfTextRun.setFontFamily("宋体");
                            }
                        }
                    }
                }                // BufferedImage对象,尺寸加倍times
                BufferedImage img = new BufferedImage(pgsize.width*times,pgsize.height*times, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.scale(times, times);// 将图片放大times倍
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width*times,pgsize.height*times));
                slides.get(i).draw(graphics);                String absolutePath = path+"/" +new GetFromFilePath().getNameFromPath(URL)+ "_"+(i + 1) + ".jpeg";
                File jpegFile = new File(absolutePath);
                if (jpegFile.exists()) {
                    continue;
                }
                FileOutputStream out = new FileOutputStream(jpegFile);
                // 写入
                ImageIO.write(img, "jpeg", out);
                out.close();
            }
            logger.debug("总耗时:"+(System.currentTimeMillis()-t1)+"ms");
            logger.debug("PPTX图片存放路径:"+"./" +new GetFromFilePath().getNameFromPath(URL));
            logger.debug("PPTX转换成功!");
            return true;
        }
        catch (Exception e) {
            logger.debug("PPTX转换异常!");
            return false;
        }
    }

Excel的转换

excel两种格式xls和xlsx对应2003和2007的版本,主要使用poi将其转换为html,通过Swing内嵌CEF进行展示。转换xls直接转换,xlsx我是通过poi将其转换为xls。

xls转换为html

public static void changeToHtml(String excelPath) {
        try{
            InputStream input = new FileInputStream(excelPath);  
            HSSFWorkbook excelBook = new HSSFWorkbook();
            //判断Excel文件版本
            if(new PPTUtil().checkXLS(new File(excelPath))){  //Excel xls 
                logger.debug("");
                excelBook = new HSSFWorkbook(input);  
            }
            else if(new PPTUtil().checkXLSX(new File(excelPath))){  // Excel  xlsx
                XlsxToXls xls = new XlsxToXls();    
                XSSFWorkbook workbookOld = new XSSFWorkbook(input); 
                xls.transformXSSF(workbookOld, excelBook);  //将xlsx转换为xls
            }  
            ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());          
            //去掉头行  
            excelToHtmlConverter.setOutputColumnHeaders(false);  
            //去掉行号 
            excelToHtmlConverter.setOutputRowNumbers(false);              excelToHtmlConverter.processWorkbook(excelBook);             Document htmlDocument = excelToHtmlConverter.getDocument();              ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
            DOMSource domSource = new DOMSource(htmlDocument);  
            StreamResult streamResult = new StreamResult(outStream);  
            TransformerFactory tf = TransformerFactory.newInstance();  
            Transformer serializer = tf.newTransformer();              serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");  
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");  
            serializer.setOutputProperty(OutputKeys.METHOD, "html");              serializer.transform(domSource, streamResult);  
            outStream.close();              //Excel转换成Html
            String content = new String(outStream.toByteArray());  
            String htmlPath = new GetFromFilePath().getNameFromPath(excelPath);
            logger.debug("excel生成html地址="+"./"+htmlPath);
            string2File(content,"./"+htmlPath+"/"+htmlPath+".html");
        }
        catch(Exception e) {
            e.printStackTrace();            
        }
    }

xlsx转换为xls

private int lastColumn = 0;  
    private HashMap<Integer, HSSFCellStyle> styleMap = new HashMap();  
    
    /**
     * Excel xlsx转换成xls
     * @param workbookOld
     * @param workbookNew
     */
    public void transformXSSF(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew) {   
        HSSFSheet sheetNew;  
        XSSFSheet sheetOld;  
 
        workbookNew.setMissingCellPolicy(workbookOld.getMissingCellPolicy());  
   
        for (int i = 0; i < workbookOld.getNumberOfSheets(); i++) {  
            sheetOld = workbookOld.getSheetAt(i);  
            sheetNew = workbookNew.getSheet(sheetOld.getSheetName());  
            sheetNew = workbookNew.createSheet(sheetOld.getSheetName());  
            this.transform(workbookOld, workbookNew, sheetOld, sheetNew);  
        }    
    }  
   
    private void transform(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew,  
            XSSFSheet sheetOld, HSSFSheet sheetNew) {  
   
        sheetNew.setDisplayFormulas(sheetOld.isDisplayFormulas());  
        sheetNew.setDisplayGridlines(sheetOld.isDisplayGridlines());  
        sheetNew.setDisplayGuts(sheetOld.getDisplayGuts());  
        sheetNew.setDisplayRowColHeadings(sheetOld.isDisplayRowColHeadings());  
        sheetNew.setDisplayZeros(sheetOld.isDisplayZeros());  
        sheetNew.setFitToPage(sheetOld.getFitToPage());  
        
        sheetNew.setHorizontallyCenter(sheetOld.getHorizontallyCenter());  
        sheetNew.setMargin(Sheet.BottomMargin,  
                sheetOld.getMargin(Sheet.BottomMargin));  
        sheetNew.setMargin(Sheet.FooterMargin,  
                sheetOld.getMargin(Sheet.FooterMargin));  
        sheetNew.setMargin(Sheet.HeaderMargin,  
                sheetOld.getMargin(Sheet.HeaderMargin));  
        sheetNew.setMargin(Sheet.LeftMargin,  
                sheetOld.getMargin(Sheet.LeftMargin));  
        sheetNew.setMargin(Sheet.RightMargin,  
                sheetOld.getMargin(Sheet.RightMargin));  
        sheetNew.setMargin(Sheet.TopMargin, sheetOld.getMargin(Sheet.TopMargin));  
        sheetNew.setPrintGridlines(sheetOld.isPrintGridlines());  
        sheetNew.setRightToLeft(sheetOld.isRightToLeft());  
        sheetNew.setRowSumsBelow(sheetOld.getRowSumsBelow());  
        sheetNew.setRowSumsRight(sheetOld.getRowSumsRight());  
        sheetNew.setVerticallyCenter(sheetOld.getVerticallyCenter());  
   
        HSSFRow rowNew;  
        for (Row row : sheetOld) {  
            rowNew = sheetNew.createRow(row.getRowNum());  
            if (rowNew != null)  
                this.transform(workbookOld, workbookNew, (XSSFRow) row, rowNew);  
        }  
   
        for (int i = 0; i < this.lastColumn; i++) {  
            sheetNew.setColumnWidth(i, sheetOld.getColumnWidth(i));  
            sheetNew.setColumnHidden(i, sheetOld.isColumnHidden(i));  
        }  
   
        for (int i = 0; i < sheetOld.getNumMergedRegions(); i++) {  
            CellRangeAddress merged = sheetOld.getMergedRegion(i);  
            sheetNew.addMergedRegion(merged);  
        }  
    }  
   
    private void transform(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew,  
            XSSFRow rowOld, HSSFRow rowNew) {  
        HSSFCell cellNew;  
        rowNew.setHeight(rowOld.getHeight());  
  
        for (Cell cell : rowOld) {  
            cellNew = rowNew.createCell(cell.getColumnIndex(),  
                    cell.getCellType());  
            if (cellNew != null)  
                this.transform(workbookOld, workbookNew, (XSSFCell) cell,  
                        cellNew);  
        }  
        this.lastColumn = Math.max(this.lastColumn, rowOld.getLastCellNum());  
    }  
   
    private void transform(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew,  
            XSSFCell cellOld, HSSFCell cellNew) {  
        cellNew.setCellComment(cellOld.getCellComment());  
   
        Integer hash = cellOld.getCellStyle().hashCode();  
        if (this.styleMap != null && !this.styleMap.containsKey(hash)) {  
            this.transform(workbookOld, workbookNew, hash,  
                    cellOld.getCellStyle(),  
                    (HSSFCellStyle) workbookNew.createCellStyle());  
        }  
        cellNew.setCellStyle(this.styleMap.get(hash));  
   
        switch (cellOld.getCellType()) {  
        case Cell.CELL_TYPE_BLANK:  
            break;  
        case Cell.CELL_TYPE_BOOLEAN:  
            cellNew.setCellValue(cellOld.getBooleanCellValue());  
            break;  
        case Cell.CELL_TYPE_ERROR:  
            cellNew.setCellValue(cellOld.getErrorCellValue());  
            break;  
        case Cell.CELL_TYPE_FORMULA:  
            cellNew.setCellValue(cellOld.getCellFormula());  
            break;  
        case Cell.CELL_TYPE_NUMERIC:  
            cellNew.setCellValue(cellOld.getNumericCellValue());  
            break;  
        case Cell.CELL_TYPE_STRING:  
            cellNew.setCellValue(cellOld.getStringCellValue());  
            break;  
        default:  
            System.out.println("transform: Unbekannter Zellentyp " 
                    + cellOld.getCellType());  
        }  
    }  
   
    private void transform(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew,  
            Integer hash, XSSFCellStyle styleOld, HSSFCellStyle styleNew) {  
        
        styleNew.setDataFormat(this.transform(workbookOld, workbookNew,  
                styleOld.getDataFormat()));  
        styleNew.setFillBackgroundColor(styleOld.getFillBackgroundColor());  
        styleNew.setFillForegroundColor(styleOld.getFillForegroundColor());  
        styleNew.setFont(this.transform(workbookNew,  
                (XSSFFont) styleOld.getFont()));  
        styleNew.setHidden(styleOld.getHidden());  
        styleNew.setIndention(styleOld.getIndention());  
        styleNew.setLocked(styleOld.getLocked());  
        styleNew.setWrapText(styleOld.getWrapText());  
        
        styleNew.setBorderBottom(styleOld.getBorderBottomEnum());
        styleNew.setBorderTop(styleOld.getBorderTopEnum());
        styleNew.setBorderLeft(styleOld.getBorderLeftEnum());
        styleNew.setBorderRight(styleOld.getBorderRightEnum());
        this.styleMap.put(hash, styleNew);  
    }  
   
    private short transform(XSSFWorkbook workbookOld, HSSFWorkbook workbookNew,  
            short index) {  
        DataFormat formatOld = workbookOld.createDataFormat();  
        DataFormat formatNew = workbookNew.createDataFormat();  
        return formatNew.getFormat(formatOld.getFormat(index));  
    }  
   
    private HSSFFont transform(HSSFWorkbook workbookNew, XSSFFont fontOld) {  
        HSSFFont fontNew = workbookNew.createFont();  
        fontNew.setBold(fontOld.getBold());  
        fontNew.setCharSet(fontOld.getCharSet());  
        fontNew.setColor(fontOld.getColor());  
        fontNew.setFontName(fontOld.getFontName());  
        fontNew.setFontHeight(fontOld.getFontHeight());  
        fontNew.setItalic(fontOld.getItalic());  
        fontNew.setStrikeout(fontOld.getStrikeout());  
        fontNew.setTypeOffset(fontOld.getTypeOffset());  
        fontNew.setUnderline(fontOld.getUnderline());  
        
        return fontNew;  
    }   
相关标签: java java