https://www.cnblogs.com/always-online/p/4800131.html
POI是 Apache 旗下一款讀寫計算機中的 word 以及 excel 文件的工具。
poi文檔官方網站https://poi.apache.org/
-
HWPF 是 POI 支持 Word(97-2003) 的 Java 組件,支持讀寫Word文檔,但是寫功能目前只實現一部分;它也提供更早版本的Word6和Word95版本的簡單的文本摘錄功能。
-
XWPF是 POI 支持 Word 2007+ 的 Java組件,提供簡單文件的讀寫功能。
- HSSF提供讀寫Microsoft Excel XLS格式檔案的功能
- XSSF提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
- HSLF提供讀寫Microsoft PowerPoint格式檔案的功能。
- HDGF提供讀Microsoft Visio格式檔案的功能。
- HPBF提供讀Microsoft Publisher格式檔案的功能。
- HSMF提供讀Microsoft Outlook格式檔案的功能。
組件圖
Apache POI發行版包括對許多文檔文件格式的支持。幾個Jar文件中提供了此支持。並非每種格式都需要所有的Jar。下表顯示了POI組件,Maven存儲庫標簽和項目的Jar文件之間的關系。
| 零件 | 應用類型 | Maven工件ID | 筆記 |
|---|---|---|---|
| POIFS | OLE2文件系統 | poi | 需要使用基於OLE2 / POIFS的文件 |
| 惠普 | OLE2屬性集 | poi | |
| 高速鋼 | Excel XLS | poi | 僅對於HSSF,如果需要通用SS,請參見下文 |
| HSLF | PowerPoint PPT | 便簽本 | |
| 硬毛PF | Word文檔 | 便簽本 | |
| 高密度纖維蛋白 | Visio VSD | 便簽本 | |
| 高爐 | 發布者PUB | 便簽本 | |
| HSMF | 展望味精 | 便簽本 | |
| DDF | 埃舍爾普通圖紙 | poi | |
| 漢王 | WMF圖紙 | 便簽本 | |
| OpenXML4J | OOXML | poi-ooxml加上poi-ooxml-schemas或 ooxml-schemas和ooxml-security |
請參閱以下注釋,了解這些選項之間的差異 |
| XSSF | Excel XLSX | poi-ooxml | |
| XSLF | PowerPoint PPTX | poi-ooxml | |
| XWPF | Word DOCX | poi-ooxml | |
| XDGF | Visio VSDX | poi-ooxml | |
| 普通SL | PowerPoint PPT和PPTX | poi-scratchpad和poi-ooxml | SL代碼位於核心POI jar中,但實現位於poi-scratchpad和poi-ooxml中。 |
| 普通SS | Excel XLS和XLSX | poi-ooxml | WorkbookFactory和朋友們都需要poi-ooxml,而不僅僅是核心poi |
docx需要依賴
<dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.document</artifactId> <version>1.0.5</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId> <version>1.0.5</version> </dependency>
doc需要依賴
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.12</version> </dependency>
讀
package com.test.word; 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.io.OutputStream; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; 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.PictureType; import org.apache.poi.xwpf.converter.core.FileImageExtractor; import org.apache.poi.xwpf.converter.core.FileURIResolver; import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter; import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.junit.Test; import org.w3c.dom.Document; /** * word 轉換成html */ public class WordToHtml { /** * 2007版本word轉換成html * @throws IOException */ @Test public void Word2007ToHtml() throws IOException { String filepath = "C:/test/"; String fileName = "滕王閣序2007.docx"; String htmlName = "滕王閣序2007.html"; final String file = filepath + fileName; File f = new File(file); if (!f.exists()) { System.out.println("Sorry File does not Exists!"); } else { if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) { // 1) 加載word文檔生成 XWPFDocument對象 InputStream in = new FileInputStream(f); XWPFDocument document = new XWPFDocument(in); // 2) 解析 XHTML配置 (這里設置IURIResolver來設置圖片存放的目錄) File imageFolderFile = new File(filepath); XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile)); options.setExtractor(new FileImageExtractor(imageFolderFile)); options.setIgnoreStylesIfUnused(false); options.setFragment(true); // 3) 將 XWPFDocument轉換成XHTML OutputStream out = new FileOutputStream(new File(filepath + htmlName)); XHTMLConverter.getInstance().convert(document, out, options); //也可以使用字符數組流獲取解析的內容 // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // XHTMLConverter.getInstance().convert(document, baos, options); // String content = baos.toString(); // System.out.println(content); // baos.close(); } else { System.out.println("Enter only MS Office 2007+ files"); } } } /** * /** * 2003版本word轉換成html * @throws IOException * @throws TransformerException * @throws ParserConfigurationException */ @Test public void Word2003ToHtml() throws IOException, TransformerException, ParserConfigurationException { String filepath = "C:/test/"; final String imagepath = "C:/test/image/"; String fileName = "滕王閣序2003.doc"; String htmlName = "滕王閣序2003.html"; final String file = filepath + fileName; InputStream input = new FileInputStream(new File(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) { File imgPath = new File(imagepath); if(!imgPath.exists()){//圖片目錄不存在則創建 imgPath.mkdirs(); } File file = new File(imagepath + suggestedName); try { OutputStream os = new FileOutputStream(file); os.write(content); os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imagepath + suggestedName; } }); //解析word文檔 wordToHtmlConverter.processDocument(wordDocument); Document htmlDocument = wordToHtmlConverter.getDocument(); File htmlFile = new File(filepath + htmlName); OutputStream outStream = new FileOutputStream(htmlFile); //也可以使用字符數組流獲取解析的內容 // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // OutputStream outStream = new BufferedOutputStream(baos); DOMSource domSource = new DOMSource(htmlDocument); StreamResult streamResult = new StreamResult(outStream); TransformerFactory factory = TransformerFactory.newInstance(); Transformer serializer = factory.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "html"); serializer.transform(domSource, streamResult); //也可以使用字符數組流獲取解析的內容 // String content = baos.toString(); // System.out.println(content); // baos.close(); outStream.close(); } }
更多參考:https://www.iteye.com/blog/elim-2031335
關於異常
無端錯誤一般都是jar包問題,jar包沖突
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
處理2003的doc(OLE2 )不能處理2007的docx(+XML),doc——HWPF,docx需要XWPF
poi操作報錯java.lang.NoSuchMethodError: org.apache.poi.util.POILogger.log(I[Ljava/lang/Object;)
這個錯誤最可能的原因是poi的jar包使用了多個版本,好吧,其實我已經把老jar包從java build path里面刪掉了,但是還有這個報錯。
有一個可以檢測class文件走哪個jar包的代碼,很不錯,以后迷茫時可以用用,這里粘過來分享下:
ClassLoader classloader =
org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getR
esource(
"org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("POI Core came from " + path);
classloader = org.apache.poi.POIXMLDocument.class.getClassLoader();
res = classloader.getResource("org/apache/poi/POIXMLDocument.class");
path = res.getPath();
System.out.println("POI OOXML came from " + path);
classloader = org.apache.poi.hslf.HSLFSlideShow.class.getClassLoader();
res = classloader.getResource("org/apache/poi/hslf/HSLFSlideShow.class");
path = res.getPath();
System.out.println("POI Scratchpad came from " + path);
檢測后,發現確實有一個class走了老包,只刪java build path沒生效。后來把workspace里面的包刪了再把project clean一下,然后重新部署,OK,問題解決了!
