天天看點

使用 Apache POI 處理 Microsoft Office 文檔

apache poi 項目的使命是創造和維護 java api 操縱各種格式的檔案,其中包括基于 office open xml 标準(ooxml)和微軟的ole 2 compound document 格式(ole2)。總之,你可以使用 java 讀寫 ms excel 檔案。此外,您可以使用 java 讀取和寫入 ms word 和 ms powerpoint 檔案。apache poi 是你的 java excel 解決方案(用于excel 97-2008)。包含了一個完整的 api 用于移植其他 ooxml 和ole2 格式。

針對每個 現存的 ms office 子產品元件,試圖提供一個共同的進階别 java api 給 ole2 和 ooxml 文檔格式。excel (ss=hssf+xssf) word (hwpf+xwpf),powerpoint (hslf+xslf),outlook (hsmf), visio (hdgf), tnef (hmef), 和 publisher (hpbf).

元件

應用類型

maven artifactid

備注

<a href="http://poi.apache.org/poifs/index.html">poifs</a>

ole2 filesystem

poi

required to work with ole2 / poifs based files

<a href="http://poi.apache.org/hpsf/index.html">hpsf</a>

ole2 property sets

<a href="http://poi.apache.org/spreadsheet/index.html">hssf</a>

excel xls

for hssf only, if common ss is needed see below

<a href="http://poi.apache.org/slideshow/index.html">hslf</a>

powerpoint ppt

poi-scratchpad

<a href="http://poi.apache.org/document/index.html">hwpf</a>

word doc

<a href="http://poi.apache.org/hdgf/index.html">hdgf</a>

visio vsd

<a href="http://poi.apache.org/hpbf/index.html">hpbf</a>

publisher pub

<a href="http://poi.apache.org/hsmf/index.html">hsmf</a>

outlook msg

<a href="http://poi.apache.org/oxml4j/index.html">openxml4j</a>

ooxml

poi-ooxml plus either poi-ooxml-schemas or

ooxml-schemas and ooxml-security

see below for differences

<a href="http://poi.apache.org/spreadsheet/index.html">xssf</a>

excel xlsx

poi-ooxml

<a href="http://poi.apache.org/slideshow/index.html">xslf</a>

powerpoint pptx

<a href="http://poi.apache.org/document/index.html">xwpf</a>

word docx

<a href="http://poi.apache.org/spreadsheet/index.html">common ss</a>

excel xls and xlsx

workbookfactory and friends all require poi-ooxml, not just core poi

下面展示使用 hssf 來建立 excle 的案例

本例子是版本 3.11

新增一個 helloworld.java

hssfworkbook() 用來建立工作簿

wb.createshee 是用來建立 sheet

有 sheet 的命名具有一定的限制性,比如,不能用 <code>*</code> 、<code>?</code> 等,為了友善、安全的命名,可以使用<code>org.apache.poi.ss.util.workbookutil#createsafesheetname</code> 方法,

建立資料 行。row 是從 0 開始的

建立 cell 放值進去

更簡單的做法是在一行代碼實作

可以用 creationhelper 處理執行個體化具體類的不同執行個體

使用 cellstyle,用來設定 cell 的樣式

最後生成 excle 檔案

效果

使用 Apache POI 處理 Microsoft Office 文檔

<a href="http://poi.apache.org/index.html">http://poi.apache.org/index.html</a>

<a href="http://poi.apache.org/overview.html#components">http://poi.apache.org/overview.html#components</a>