Java:Java的jar包之POI的简介、安装、使用方法(基于POI将Word、Excel、PPT转换为html)之详细攻略

Java:Java的jar包之POI的简介、安装、使用方法(基于POI的转换—Word、Excel、Ppt等转html)之详细攻略


POI的简介

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。Poor Obfuscation Implementation即 简洁版的模糊实现。

1、基本功能

  • HSSF - 提供读写Microsoft Excel格式档案的功能。
  • XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。
  • HWPF - 提供读写Microsoft Word格式档案的功能。
  • HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
  • HDGF - 提供读写Microsoft Visio格式档案的功能。

POI的安装

下载地址:https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-4.0.0-20180907.tar.gz

% gpg --import KEYS
% gpg --verify downloaded_file.asc downloaded_file
or

% pgpk -a KEYS
% pgpv downloaded_file.asc
or

% pgp -ka KEYS
% pgp downloaded_file.asc

POI的使用方法(基于POI的转换—Word、Excel、Ppt等转html)

1、基础案例

1.1、创建Excel 文档—利用Jakarta POI API 创建Excel 文档

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileOutputStream;
public class CreateXL {
    /** Excel 文件要存放的位置,假定在D盘下*/
    public static String outputFile = "D:\\test.xls";
    public static void main(String argv[]) {
        try {
            // 创建新的Excel 工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 在Excel工作簿中建一工作表,其名为缺省值
            // 如要新建一名为"效益指标"的工作表,其语句为:
            // HSSFSheet sheet = workbook.createSheet("效益指标");
            HSSFSheet sheet = workbook.createSheet();
            // 在索引0的位置创建行(最顶端的行)
            HSSFRow row = sheet.createRow((short)0);
            //在索引0的位置创建单元格(左上端)
            HSSFCell cell = row.createCell((short)0);
            // 定义单元格为字符串类型
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);//已过时
            // 在单元格中输入一些内容
            cell.setCellValue("增加值");
            // 新建一输出文件流
            FileOutputStream fOut = new FileOutputStream(outputFile);
            // 把相应的Excel 工作簿存盘
            workbook.write(fOut);
            fOut.flush();
            // 操作结束,关闭文件
            fOut.close();
            System.out.println("文件生成...");
        } catch (Exception e) {
            System.out.println("已运行 xlCreate() : " + e);
        }
    }
}

1.2、读取Excel文档中的数据

读取Excel文档中的数据。假定在D盘JTest目录下有一个文件名为test1.xls的Excel文件。

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
public class ReadXL {
    /** Excel文件的存放位置。注意是反斜线*/
    public static String fileToBeRead = "D:\\test1.xls";
    public static void main(String argv[]) {
        try {
            // 创建对Excel工作簿文件的引用
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
            // 创建对工作表的引用。
            // 本例是按名引用(让我们假定那张表有着缺省名"Sheet1")
            HSSFSheet sheet = workbook.getSheet("Sheet1");
            // 也可用getSheetAt(int index)按索引引用,
            // 在Excel文档中,第一张工作表的缺省索引是0,
            // 其语句为:HSSFSheet sheet = workbook.getSheetAt(0);
            // 读取左上端单元
            HSSFRow row = sheet.getRow(0);
            HSSFCell cell = row.getCell((short)0);
            // 输出单元内容,cell.getStringCellValue()就是取所在单元的值
            System.out.println("左上端单元是: " + cell.getStringCellValue());
        } catch (Exception e) {
            System.out.println("已运行xlRead() : " + e);
        }
    }
}

1.3、处理WORD文档

import java.io. * ;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class TestPoi {
    public TestPoi() {}
    public static void main(String args[])throws Exception{
        FileInputStream in = new FileInputStream("D:\\a.doc");
        WordExtractor extractor = new WordExtractor();
        String str = extractor.extractText(in);
        //System.out.println("the result length is"+str.length());
        System.out.println(str);
    }
}

2、进阶案例应用

文章参考
https://blog.csdn.net/yjclsx/article/details/51441632
http://blog.csdn.net/z69183787/article/details/17468039

在现在这个互联网在线时代,java实现在线预览的这个需求,或许是大家都想要的。当然,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,比如永中office、office web 365(http://www.officeweb365.com/)等公司,都有云端在线预览服务,可想而知,这些扩展功能,肯定是需要钱了。
          但是,对于我们学生党,如果想要免费或者DIY,则可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行。实现原理就是:

  • 1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
  • 2.通过swfTools将pdf文件转换成swf格式的文件;
  • 3.通过FlexPaper文档组件在页面上进行展示。

当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
          当然,本篇文章主要介绍的POI,所以,可以通过POI实现word、excel、ppt转html,这样就可以放在页面上了。

2.1、word转html

package wordToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiWordToHtml {
 public static void main(String[] args) throws Throwable {
  final String path = "D:\\poi-test\\wordToHtml\\";
  final String file = "人员选择系分.doc";
  InputStream input = new FileInputStream(path + file);
  HWPFDocument wordDocument = new HWPFDocument(input);
  WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    DocumentBuilderFactory.newInstance().newDocumentBuilder()
      .newDocument());
  wordToHtmlConverter.setPicturesManager(new PicturesManager() {
   public String savePicture(byte[] content, PictureType pictureType,
     String suggestedName, float widthInches, float heightInches) {
    return suggestedName;
   }
  });
  wordToHtmlConverter.processDocument(wordDocument);
  List pics = wordDocument.getPicturesTable().getAllPictures();
  if (pics != null) {
   for (int i = 0; i < pics.size(); i++) {
    Picture pic = (Picture) pics.get(i);
    try {
     pic.writeImageContent(new FileOutputStream(path
       + pic.suggestFullFileName()));
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    }
   }
  }
  Document htmlDocument = wordToHtmlConverter.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, "utf-8");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.METHOD, "html");
  serializer.transform(domSource, streamResult);
  outStream.close();
  String content = new String(outStream.toByteArray());
  FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
 }
}

2.2、excel转html

package excelToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

public class PoiExcelToHtml {
final static String path = "D:\\poi-test\\excelToHtml\\";
 final static String file = "exportExcel.xls";
 public static void main(String args[]) throws Exception {

 InputStream input=new FileInputStream(path+file);
 HSSFWorkbook excelBook=new HSSFWorkbook(input);
 ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
 excelToHtmlConverter.processWorkbook(excelBook);
 List pics = excelBook.getAllPictures();
     if (pics != null) {
         for (int i = 0; i < pics.size(); i++) {
             Picture pic = (Picture) pics.get (i);
             try {
                 pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
         }
     }
     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, "utf-8");
     serializer.setOutputProperty (OutputKeys.INDENT, "yes");
     serializer.setOutputProperty (OutputKeys.METHOD, "html");
     serializer.transform (domSource, streamResult);
     outStream.close();

     String content = new String (outStream.toByteArray() );

     FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
 }
}

2.3、ppt转html

其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。ppt转图片有个缺陷,就是ppt里不是宋体的字有些可能会变成框框。以上都需要引入poi的jar包。要实现在线预览,只需把转换得到的html在新标签页打开或者镶嵌到某块区域就可以展现了。

package pptToImg;

import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;   

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;   

import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.record.Slide;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;   

public class PPTtoImage {
    public static void main(String[] args) {
        // 读入PPT文件
        File file = new File("D:/poi-test/pptToImg/test.ppt");
        doPPTtoImage(file);
    }   

    public static boolean doPPTtoImage(File file) {
        boolean isppt = checkFile(file);
        if (!isppt) {
            System.out.println("The image you specify don't exit!");
            return false;
        }
        try {   

            FileInputStream is = new FileInputStream(file);
            SlideShow ppt = new SlideShow(is);
            is.close();
            Dimension pgsize = ppt.getPageSize();
            org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                System.out.print("第" + i + "页。");   

                TextRun[] truns = slide[i].getTextRuns();
                for ( int k=0;k<truns.length;k++){
                   RichTextRun[] rtruns = truns[k].getRichTextRuns();
                  for(int l=0;l<rtruns.length;l++){
                       int index = rtruns[l].getFontIndex();
                        String name = rtruns[l].getFontName();
                        rtruns[l].setFontIndex(1);
                        rtruns[l].setFontName("宋体");
//                        System.out.println(rtruns[l].getText());
                   }
                }
                BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);   

                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.BLUE);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);   

                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
                FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");
                javax.imageio.ImageIO.write(img, "jpeg", out);
                out.close();   

            }
            System.out.println("success!!");
            return true;
        } catch (FileNotFoundException e) {
            System.out.println(e);
            // System.out.println("Can't find the image!");
        } catch (IOException e) {
        }
        return false;
    }   

    // function 检查文件是否为PPT
    public static boolean checkFile(File file) {   

        boolean isppt = false;
        String filename = file.getName();
        String suffixname = null;
        if (filename != null && filename.indexOf(".") != -1) {
            suffixname = filename.substring(filename.indexOf("."));
            if (suffixname.equals(".ppt")) {
                isppt = true;
            }
            return isppt;
        } else {
            return isppt;
        }
    }   

}

参考文章
百度百科

(0)

相关推荐