apache poi 生成excel怎么根据集合长度生成多个word页面

使用Apache POI抽取OFFICE文本(DOC, DOCX, XLS, XLSX, PPT, PPTX)——Desktop Search开发笔记【经验积累】 - 推酷
使用Apache POI抽取OFFICE文本(DOC, DOCX, XLS, XLSX, PPT, PPTX)——Desktop Search开发笔记【经验积累】
为了对文件内容进行索引,必须先抽取出文件中文本。我们使用Apache POI提供的API来抽取office文件(DOC, DOCX, XLS, XLSX, PPT, PPTX)中的文本。很多人在文件使用开源API的时候都很纳闷,Javadocs那么大,我要的API在到底在那个类里边。即使找到了也不明白这么多构造函数该用哪个创建想要的对象。本文给大家讲一下POI中我们该如何创建抽取(DOC, DOCX, XLS, XLSX, PPT, PPTX)的对象。
下载Apache POI(
把下面5个jar包和两个lib文件夹中的jar导入项目classpath
poi-3.10-beta1-.jar
poi-excelant-3.10-beta1-.jar
poi-ooxml-3.10-beta1-.jar
poi-ooxml-schemas-3.10-beta1-.jar
poi-scratchpad-3.10-beta1-.jar
/ooxml-lib
org.apache.poi.hwpf.extractor.WordExtractor
这个类只能处理word 2003文档(.doc)
& & &(1) 使用ExtractorFactory.createExtractor(InputStream) 创建抽取对象,返回的是公共接口对象,因此强制转换
& & & & & & & &InputStream fis = new FileInputStream(filePath);
& & & & & & & &WorderExtractor extractor = (WordExtractor) ExtractorFactory.createExtractor(fis);
& & &(2) 使用WordExtractor创建抽取对象
& & & & & & & &&
& & & & & & & & 介绍一下最后两种:
& & & & & & & & 最后第二种接收InputStream来创建对象;
& & & & & & & & 最后一种接收POIFSFileSystem来创建对象:
& & & & & & & & & & & &&
& & & & & & & & & & & & &POIFSFileSystem也接收InputStream来接收对象。
& & & & & & & & &
& & & & & & & & &回过头来看看最后第三个构造函数,接收HWPFDocument来创建对象;
& & & & & & & & & & & & &
& & & & & & & & & & & & &而HWPFDDocument通过接收InputStream或者POIFSFileSystem来创建对象。
org.apache.poi.POITextExtractor
org.apache.poi.POIXMLTextExtractor
org.apache.poi.xwpf.extractor.XWPFWordExtractor
这个类能够处理excel2007+(.docx)
& & &(1)该类对象的父类可以使用ExtratorFactory生成,但需要接收的参数是个virtual 对象OPCPackage,该对象不好确定。因此我们直接使用(2)中的方法创建对象
& & &(2)新建XWPFWordExtractor对象
& & & & & & & &
& & & & & & & & 我们使用第二个构造函数,通过接收XWPFDocument对象来创建
& & & & & & & & & & &
& & & & & & & & & & & XWPFDocument可以接收inputStream对象。
org.apache.poi.hssf.extractor.ExcelExtractor
&这个类只能处理excel 2003(.xls)
& & &(1)同DOC,通过ExtractorFactory创建
& & &(2)新建ExcelExtractor对象
& & & & & & & &
& & & & & & & &1)同DOC,通过接收POIFSFileSystem来创建对象
& & & & & & & &2)通过接收HSSFWorkbook来创建对象
& & & & & & & & & &&
& & & & & & & & & & HSSFWorkbook对象可以通过接收POIFSFileSystem或者InputStream对象来创建
& & & & & & & &
& & & & & &
样例代码:
org.apache.poi.POITextExtractor
org.apache.poi.POIXMLTextExtractor
& & & & &直接新建XSSFExcelExtractor对象:
& & & & & & & &
& & & & & & & &通过接收XSSFWorkbook对象来创建:
& & & & & & & & & &&
& & & & & & & & & & &发现XSSFWorkbook可以接收inputStream对象
org.apache.poi.hslf.extractor.PowerPointExtractor
& & & & & (1)同DOC,用ExtractorFactory创建对象
& & & & & (2)直接使用PowerPointExtractor创建对象
& & & & & & &
& & & & & & & &通过接收HSLFSlideShow对象、POIFSFileSystem对象或文件名即可创建。 & & & & & & &&
org.apache.poi.POITextExtractor
org.apache.poi.POIXMLTextExtractor
& & & & & &同XLSX,直接创建XSLFPowerPointExtractor对象
& & & & & & & &
& & & & & & & &(1)接收XMLSlideShow对象
& & & & & & & & & & & & &
& & & & & & & & & & & & & & &通过接收InputStream来创建XMLSlideShow对象
& & & & & & & &(2)接收XSLFSlideShow对象
& & & & & & & & & & & & & &
& & & & & & & & & & & & & & & 通过接收文件路径即可创建XSLFSlideShow对象
已发表评论数()
&&登&&&录&&
已收藏到推刊!
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见当前访客身份:游客 [
个人能力是创造价值的体现,虽然我还没有开始为你创造价值,但是我的能力是未来能给你创造价值的资本。
:引用来自“小小小七”的评论这个和dubbo 有啥区别...
:这个和dubbo 有啥区别吗?
:引用来自“辣条冰袋专卖”的评论66666咋了?
今日访问:2
昨日访问:13
本周访问:2
本月访问:607
所有访问:5915
ApachePOI 动态列表生成excel
发表于5个月前( 18:22)&&
阅读(146)&|&评论()
0人收藏此文章,
传入需要生成excel表格的List实体集合,通过反射动态生成excel,不需要再工具类中编码实现,以便不同的实体集合也能使用工具类
先创建导出Excel的工具类,并带泛型,实体一定要生成属性的get方法,就是普通的Javabean,后面的就是个人发挥了,废话不多说,直接上代码:
public&class&ExportExcel&T&&{
public&void&exportExcel(Collection&T&&dataset,&OutputStream&out)&{
&&&&&&exportExcel("数据导出",&null,&dataset,&out,&"yyyy-MM-dd&hh:MM:ss");
&&&public&void&exportExcel(String[]&headers,&Collection&T&&dataset,
&&&&&&&&&OutputStream&out)&{
&&&&&&exportExcel("数据导出",&headers,&dataset,&out,&"yyyy-MM-dd&hh:MM:ss");
&&&public&void&exportExcel(String[]&headers,&Collection&T&&dataset,
&&&&&&&&&OutputStream&out,&String&pattern)&{
&&&&&&exportExcel("数据导出",&headers,&dataset,&out,&pattern);
&&&public&void&exportExcel(String&title,&String[]&headers,
&&&&&&&&&Collection&T&&dataset,&OutputStream&out,&String&pattern)&{
&&&&&&//&声明一个工作薄
&&&&&&HSSFWorkbook&workbook&=&new&HSSFWorkbook();
&&&&&&//&生成一个表格
&&&&&&HSSFSheet&sheet&=&workbook.createSheet(title);
&&&&&&//&设置表格默认列宽度为30个字节
&&&&&&sheet.setDefaultColumnWidth(30);
&&&&&&//&生成一个样式
&&&&&&HSSFCellStyle&style&=&workbook.createCellStyle();
&&&&&&//&设置这些样式
&&&&&&style.setFillForegroundColor(HSSFColor.WHITE.index);
&&&&&&style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
&&&&&&style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
&&&&&&style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
&&&&&&style.setBorderRight(HSSFCellStyle.BORDER_THIN);
&&&&&&style.setBorderTop(HSSFCellStyle.BORDER_THIN);
&&&&&&style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
&&&&&&//&标题字体
&&&&&&HSSFFont&font&=&workbook.createFont();
&&&&&&font.setColor(HSSFColor.BLACK.index);
&&&&&&font.setFontHeightInPoints((short)&12);
&&&&&&font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
&&&&&&//&把字体应用到当前的样式
&&&&&&style.setFont(font);
&&&&&&//&生成并设置另一个样式
&&&&&&HSSFCellStyle&style2&=&workbook.createCellStyle();
&&&&&&style2.setFillForegroundColor(HSSFColor.WHITE.index);
&&&&&&style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
&&&&&&style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
&&&&&&style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
&&&&&&style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
&&&&&&style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
&&&&&&style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
&&&&&&style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
&&&&&&//&内容字体
&&&&&&HSSFFont&font2&=&workbook.createFont();
&&&&&&font2.setColor(HSSFColor.BLACK.index);
&&&&&&font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
&&&&&&//&把字体应用到当前的样式
&&&&&&style2.setFont(font2);
&&&&&&//&声明一个画图的顶级管理器
&&&&&&HSSFPatriarch&patriarch&=&sheet.createDrawingPatriarch();
&&&&&&//&定义注释的大小和位置,详见文档
&&&&&&HSSFComment&comment&=&patriarch.createComment(new&HSSFClientAnchor(0,&0,&0,&0,&(short)&4,&2,&(short)&6,&5));
&&&&&&//&设置注释内容
&&&&&&comment.setString(new&HSSFRichTextString("注释!"));
&&&&&&//&设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
&&&&&&comment.setAuthor("yuyidi");
&&&&&&//产生表格标题行
&&&&&&HSSFRow&row&=&sheet.createRow(0);
&&&&&&for&(int&i&=&0;&i&&&headers.&i++)&{
&&&&&&&&&HSSFCell&cell&=&row.createCell(i);
&&&&&&&&&cell.setCellStyle(style);
&&&&&&&&&HSSFRichTextString&text&=&new&HSSFRichTextString(headers[i]);
&&&&&&&&&cell.setCellValue(text);
&&&&&&//遍历集合数据,产生数据行
&&&&&&Iterator&T&&it&=&dataset.iterator();
&&&&&&int&index&=&0;
&&&&&&while&(it.hasNext())&{
&&&&&&&&&index++;
&&&&&&&&&row&=&sheet.createRow(index);
&&&&&&&&&T&t&=&(T)&it.next();
&&&&&&&&&//利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
&&&&&&&&&Field[]&fields&=&t.getClass().getDeclaredFields();
&&&&&&&&&for&(int&i&=&0;&i&&&fields.&i++)&{
&&&&&&&&&&&&HSSFCell&cell&=&row.createCell(i);
&&&&&&&&&&&&cell.setCellStyle(style2);
&&&&&&&&&&&&Field&field&=&fields[i];
&&&&&&&&&&&&String&fieldName&=&field.getName();
&&&&&&&&&&&&String&getMethodName&=&"get"
&&&&&&&&&&&&&&&&&&&+&fieldName.substring(0,&1).toUpperCase()
&&&&&&&&&&&&&&&&&&&+&fieldName.substring(1);
&&&&&&&&&&&&try&{
&&&&&&&&&&&&&&&&Class&tCls&=&t.getClass();
&&&&&&&&&&&&&&&&Method&getMethod&=&tCls.getMethod(getMethodName,
&&&&&&&&&&&&&&&&&&&&&&new&Class[]&{});
&&&&&&&&&&&&&&&&Object&value&=&getMethod.invoke(t,&new&Object[]&{});
&&&&&&&&&&&&&&&&//判断值的类型后进行强制类型转换
&&&&&&&&&&&&&&&&String&textValue&=&
&&&&&&&&&&&&&&&if&(value&instanceof&Date)&{
&&&&&&&&&&&&&&&&&&&Date&date&=&(Date)&
&&&&&&&&&&&&&&&&&&&SimpleDateFormat&sdf&=&new&SimpleDateFormat(pattern);
&&&&&&&&&&&&&&&&&&&&textValue&=&sdf.format(date);
&&&&&&&&&&&&&&&}else&if&(value&instanceof&Double)&{
&&&&&&&&&&&&textValue&=&formatter.format(value);
&&&&&&&&&&&&&&&&}&&else&if&(value&instanceof&byte[])&{
&&&&&&&&&&&&&&&&&&&//&有图片时,设置行高为60
&&&&&&&&&&&&&&&&&&&row.setHeightInPoints(60);
&&&&&&&&&&&&&&&&&&&//&设置图片所在列宽度为80px,注意这里单位的一个换算
&&&&&&&&&&&&&&&&&&&sheet.setColumnWidth(i,&(short)&(35.7&*&80));
&&&&&&&&&&&&&&&&&&&//&sheet.autoSizeColumn(i);
&&&&&&&&&&&&&&&&&&&byte[]&bsValue&=&(byte[])&
&&&&&&&&&&&&&&&&&&&HSSFClientAnchor&anchor&=&new&HSSFClientAnchor(0,&0,
&&&&&&&&&&&&&&&&&&&&&&&&&,&(short)&6,&index,&(short)&6,&index);
&&&&&&&&&&&&&&&&&&&anchor.setAnchorType(2);
&&&&&&&&&&&&&&&&&&&patriarch.createPicture(anchor,&workbook.addPicture(
&&&&&&&&&&&&&&&&&&&&&&&&&bsValue,&HSSFWorkbook.PICTURE_TYPE_JPEG));
&&&&&&&&&&&&&&&&}&else{
&&&&&&&&&&&&&&&&&&&//其它数据类型都当作字符串简单处理
&&&&&&&&&&&&&&&&&&&textValue&=&objToString(value);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&//如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
&&&&&&&&&&&&&&&&if(textValue!=null){
&&&&&&&&&&&&&&&&&&&Pattern&p&=&pile("^//d+(//.//d+)?$");&&
&&&&&&&&&&&&&&&&&&&Matcher&matcher&=&p.matcher(textValue);
&&&&&&&&&&&&&&&&&&&if(matcher.matches()){
&&&&&&&&&&&&&&&&&&&&&&//是数字当作double处理
&&&&&&&&&&&&&&&&&&&&&&cell.setCellValue(Double.parseDouble(textValue));
&&&&&&&&&&&&&&&&&&&}else{
&&&&&&&&&&&&&&&&&&&&&&HSSFRichTextString&richString&=&new&HSSFRichTextString(textValue);
&&&&&&&&&&&&&&&&&&&&&&cell.setCellValue(richString);
&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}&catch&(SecurityException&e)&{
&&&&&&&&&&&&&&&&e.printStackTrace();
&&&&&&&&&&&&}&catch&(NoSuchMethodException&e)&{
&&&&&&&&&&&&&&&&e.printStackTrace();
&&&&&&&&&&&&}&catch&(IllegalArgumentException&e)&{
&&&&&&&&&&&&&&&&e.printStackTrace();
&&&&&&&&&&&&}&catch&(IllegalAccessException&e)&{
&&&&&&&&&&&&&&&&e.printStackTrace();
&&&&&&&&&&&&}&catch&(InvocationTargetException&e)&{
&&&&&&&&&&&&&&&&e.printStackTrace();
&&&&&&&&&&&&}&finally&{
&&&&&&&&&&&&&&&&//清理资源
&&&&&&&&&&&&}
&&&&&&&&&}
&&&&&&&&&&cellindex&=&0;
&&&&&&try&{
&&&&&&&&&workbook.write(out);
&&&&&&}&catch&(IOException&e)&{
&&&&&&&&&e.printStackTrace();
&&&private&String&objToString(Object&obj){
&&&&return&(obj&==&null)&?&""&:&obj.toString();
更多开发者职位上
1)">1)">1" ng-class="{current:{{currentPage==page}}}" ng-repeat="page in pages"><li class='page' ng-if="(endIndex<li class='page next' ng-if="(currentPage
相关文章阅读使用Apache POI和OpenOffice API在Linux中统计Office文档的页数 - 其它语言 - 编程入门网
使用Apache POI和OpenOffice API在Linux中统计Office文档的页数
Apache POI 介绍
Apache POI 是一套用于访问微软 Office 格式文档 (Word, Excel and PowerPoint) 的 Java API。其中用于操作 Excel 格式文件的 API 是 HSSF,用于操作 Word 格式文件的 API 是 HWPF 以及用于操作 PowerPoint 格式文件的 API 是 HSLF。
POI 的官方网站是 http://poi.apache.org,用户可以先从这里下载最新的版本 3.6, 下载解压后里面有三个 jar 包(poi-3.6-.jar,poi-contrib-3.6-.jar 和 poi-scratchpad-3.6- .jar)将这三个 jar 包拷贝至 Eclipse 工程的 lib 目录中,然后刷新工程即可加载 POI 的类库。
POI 主要组成部分
POIFS:POIFS 是该项目的最古老,最稳定的一部分,它同时支持读写功能,所有的组件最终都依赖于 它的定义。
POIFS 对于 OLE 2 文件操作: POIFS 的基础是最古老和最稳定的项目的一部分。这是我们的 OLE 2 复 合文档格式的纯 Java 实现。它同时支持阅读和书写功能。我们的组成部分都最终依赖于它的定义。更多信息请参阅 POIFS 项目页。
HSSF 对于 Excel 文件操作:HSSF 是针对 Microsoft Excel 97(-2003)文件格式(BIFF8)的文档操作 的纯 Java 实现。它支持阅读和书写能力。更多信息请参阅 HSSF 项目页。
HWPF 对于 Word 文件操作:HWPF 是针 对 Microsoft Word 97 文件格式的文档操作的纯 Java 接口。该组件是在发展的初期阶段,对 word 文档的读写能力有限 ,仅仅可以阅读和书写简单的 word 文件,更多信息 HWPF 请参阅 HWPF 的项目页。
HSLF 对于 PowerPoint 文件操 作:HSLF 是针对 Microsoft PowerPoint 97(-2003)文件格式的文档操作的纯 Java 接口。它支持阅读和书写能力。更多 信息请参阅 HSLF 项目页。
HDGF 对于 Visio 文件操作:除此之外 POI 还提供了 HDGF 对微软 Visio97(-2003) 文件格式的文档操作的纯 Java 接口。它目前只支持读取操作,在一个很低的水平,只支持简单的文本提取。更多信息请参 阅 HDGF 项目页。
HPSF 文档属性:HPSF 是这对 OLE 2 设置格式的纯 Java 接口。主要是用来存储文件的属性集( 如:标题,作者,最后修改日期等属性),他们可以为特定应用目的所使用。更多信息请参阅 HPSF 项目页。
下面 我们简单的介绍一下项目中经常会使用到的对于 Excel 和 Word 格式文件进行操作的接口:
目前 POI 比较成熟的部分是 HSSF 接口,处理 MS Excel(97-2003)对象。它不像我们仅仅使用 csv 生成的没有格式的可以由 Excel 转换的东西,而是真正的 Excel 对象,你可以控制一些属性如 cell,sheet 等等。当然,HSSF 也有一些缺点,比 如不能直接支持 Excel 图表,包与包之间依赖关系比较复杂等等。
对于统计页数 (sheet 个数 ) 来说,HSSF 接口 可以很简单的完成这一功能。下面我们简单的介绍一下 HSSF 接口:
HSSF 提供给我们使用的对象在 org.apache.poi.hssf.usermodel 包中,主要部分包括 Excel 对象,样式和格式,还有辅助操作。主要有以下几种对象:
HSSFWorkbook: 对应于 Excel 的文档对象
HSSFSheet: 对应于 Excel 的表单
HSSFRow: 对应于 Excel 的行
HSSFCell: 对应于 Excel 的格子单元
HSSFFont: 对应于 Excel 字体
HSSFName: 对应 于 Excel 名称
HSSFDataFormat: 对应于日期格式
HSSFHeader: 对应于 Sheet 头
HSSFFooter: 对 应于 Sheet 尾
HSSFCellStyle: 对应于 Cell 样式
辅助操作包括:
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表18864人阅读
最近公司做的项目需要实现导出Word文档的功能,网上关于POI生成Word文档的例子很少,找了半天才在官网里找到个Demo,有了Demo一切就好办了。
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.
See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the &License&); you may not use this file except in compliance with
the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an &AS IS& BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xwpf.
import java.io.FileOutputS
* A simple WOrdprocessingML document created by POI XWPF API
* @author Yegor Kozlov
public class SimpleDocument {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p1 = doc.createParagraph();
p1.setAlignment(ParagraphAlignment.CENTER);
p1.setBorderBottom(Borders.DOUBLE);
p1.setBorderTop(Borders.DOUBLE);
p1.setBorderRight(Borders.DOUBLE);
p1.setBorderLeft(Borders.DOUBLE);
p1.setBorderBetween(Borders.SINGLE);
p1.setVerticalAlignment(TextAlignment.TOP);
XWPFRun r1 = p1.createRun();
r1.setBold(true);
r1.setText(&The quick brown fox&);
r1.setBold(true);
r1.setFontFamily(&Courier&);
r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
r1.setTextPosition(100);
XWPFParagraph p2 = doc.createParagraph();
p2.setAlignment(ParagraphAlignment.RIGHT);
p2.setBorderBottom(Borders.DOUBLE);
p2.setBorderTop(Borders.DOUBLE);
p2.setBorderRight(Borders.DOUBLE);
p2.setBorderLeft(Borders.DOUBLE);
p2.setBorderBetween(Borders.SINGLE);
XWPFRun r2 = p2.createRun();
r2.setText(&jumped over the lazy dog&);
r2.setStrike(true);
r2.setFontSize(20);
XWPFRun r3 = p2.createRun();
r3.setText(&and went away&);
r3.setStrike(true);
r3.setFontSize(20);
r3.setSubscript(VerticalAlign.SUPERSCRIPT);
XWPFParagraph p3 = doc.createParagraph();
p3.setWordWrap(true);
p3.setPageBreak(true);
//p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
p3.setAlignment(ParagraphAlignment.BOTH);
p3.setSpacingLineRule(LineSpacingRule.EXACT);
p3.setIndentationFirstLine(600);
XWPFRun r4 = p3.createRun();
r4.setTextPosition(20);
r4.setText(&To be, or not to be: that is the question: &
+ &Whether 'tis nobler in the mind to suffer &
+ &The slings and arrows of outrageous fortune, &
+ &Or to take arms against a sea of troubles, &
+ &And by opposing end them? To die: &);
r4.addBreak(BreakType.PAGE);
r4.setText(&N and by a sleep to say we end &
+ &The heart-ache and the thousand natural shocks &
+ &That flesh is heir to, 'tis a consummation &
+ &Devoutly to be wish'd. To die, &
+ &To sleep: perchance to dream: ay, there' &
+ &.......&);
r4.setItalic(true);
//This would imply that this break shall be treated as a simple line break, and break the line after that word:
XWPFRun r5 = p3.createRun();
r5.setTextPosition(-10);
r5.setText(&For in that sleep of death what dreams may come&);
r5.addCarriageReturn();
r5.setText(&When we have shuffled off this mortal coil,&
+ &Must give us pause: there's the respect&
+ &That makes cala&);
r5.addBreak();
r5.setText(&For who would bear the whips and scorns of time,&
+ &The oppressor's wrong, the proud man's contumely,&);
r5.addBreak(BreakClear.ALL);
r5.setText(&The pangs of despised love, the law's delay,&
+ &The insolence of office and the spurns& + &.......&);
FileOutputStream out = new FileOutputStream(&simple.docx&);
doc.write(out);
out.close();
版权声明:本文为博主原创文章,未经博主允许不得转载。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:76246次
排名:千里之外
原创:10篇
转载:11篇
评论:15条
(1)(1)(1)(2)(3)(1)(2)(3)(1)(1)(1)(3)(1)如何通过apache POI技术来读取Word文档,并把Word文档的原来格式完整地显示在html网页?-问答-最代码
完如何通过apache POI技术来读取Word文档,并把Word文档的原来格式完整地显示在html网页?
POI技术来读取Word文档,并把Word文档的原来格式完整地显示在html网页?
所有回答列表(2)
我把代码发到你的邮箱。
package com.my.
import java.io.BufferedW
import java.io.F
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.FileOutputS
import java.io.IOE
import java.io.OutputS
import java.io.OutputStreamW
import org.apache.poi.hwpf.HWPFD
import org.apache.poi.hwpf.model.PicturesT
import org.apache.poi.hwpf.usermodel.CharacterR
import org.apache.poi.hwpf.usermodel.P
import org.apache.poi.hwpf.usermodel.P
import org.apache.poi.hwpf.usermodel.R
import org.apache.poi.hwpf.usermodel.T
import org.apache.poi.hwpf.usermodel.TableC
import org.apache.poi.hwpf.usermodel.TableI
import org.apache.poi.hwpf.usermodel.TableR
public class WordExcelToHtml1 {
&& & * 回车符ASCII码
&& &private static final short ENTER_ASCII = 13;
&& & * 空格符ASCII码
&& &private static final short SPACE_ASCII = 32;
&& & * 水平制表符ASCII码
&& &private static final short TABULATION_ASCII = 9;
&& &public static String htmlText = &&;
&& &public static String htmlTextTbl = &&;
&& &public static int counter = 0;
&& &public static int beginPosi = 0;
&& &public static int endPosi = 0;
&& &public static int beginArray[];
&& &public static int endArray[];
&& &public static String htmlTextArray[];
&& &public static boolean tblExist =
&& &public static final String inputFile = &c://cc.doc&;
&& &public static void main(String argv[]) {
&& &&& &try {
&& &&& &&& &getWordAndStyle(inputFile);
&& &&& &} catch (Exception e) {
&& &&& &&& &e.printStackTrace();
&& & * 读取每个文字样式
&& & * @param fileName
&& & * @throws Exception
&& &public static void getWordAndStyle(String fileName) throws Exception {
&& &&& &FileInputStream in = new FileInputStream(new File(fileName));
&& &&& &HWPFDocument doc = new HWPFDocument(in);
&& &&& &Range rangetbl = doc.getRange();// 得到文档的读取范围
&& &&& &TableIterator it = new TableIterator(rangetbl);
&& &&& &int num = 100;
&& &&& &beginArray = new int[num];
&& &&& &endArray = new int[num];
&& &&& &htmlTextArray = new String[num];
&& &&& &// 取得文档中字符的总数
&& &&& &int length = doc.characterLength();
&& &&& &// 创建图片容器
&& &&& &PicturesTable pTable = doc.getPicturesTable();
&& &&& &htmlText = &&html&&head&&title&&
&& &&& &&& &&& &+ doc.getSummaryInformation().getTitle()
&& &&& &&& &&& &+ &&/title&&/head&&body&&;
&& &&& &// 创建临时字符串,好加以判断一串字符是否存在相同格式
&& &&& &if (it.hasNext()) {
&& &&& &&& &readTable(it, rangetbl);
&& &&& &int cur = 0;
&& &&& &String tempString = &&;
&& &&& &for (int i = 0; i & length - 1; i++) {
&& &&& &&& &// 整篇文章的字符通过一个个字符的来判断,range为得到文档的范围
&& &&& &&& &Range range = new Range(i, i + 1, doc);
&& &&& &&& &CharacterRun cr = range.getCharacterRun(0);
&& &&& &&& &if (tblExist) {
&& &&& &&& &&& &if (i == beginArray[cur]) {
&& &&& &&& &&& &&& &htmlText += tempString + htmlTextArray[cur];
&& &&& &&& &&& &&& &tempString = &&;
&& &&& &&& &&& &&& &i = endArray[cur] - 1;
&& &&& &&& &&& &&& &cur++;
&& &&& &&& &&& &&& &
&& &&& &&& &&& &}
&& &&& &&& &}
&& &&& &&& &if (pTable.hasPicture(cr)) {
&& &&& &&& &&& &htmlText += tempS
&& &&& &&& &&& &// 读写图片
&& &&& &&& &&& &readPicture(pTable, cr);
&& &&& &&& &&& &tempString = &&;
&& &&& &&& &} else {
&& &&& &&& &&& &Range range2 = new Range(i + 1, i + 2, doc);
&& &&& &&& &&& &// 第二个字符
&& &&& &&& &&& &CharacterRun cr2 = range2.getCharacterRun(0);
&& &&& &&& &&& &char c = cr.text().charAt(0);
&& &&& &&& &&& &System.out.println(i + &::& + range.getEndOffset() + &::&
&& &&& &&& &&& &&& &&& &+ range.getStartOffset() + &::& + c);
&& &&& &&& &&& &// 判断是否为回车符
&& &&& &&& &&& &if (c == ENTER_ASCII) {
&& &&& &&& &&& &&& &tempString += &&br/&&;
&& &&& &&& &&& &}
&& &&& &&& &&& &// 判断是否为空格符
&& &&& &&& &&& &else if (c == SPACE_ASCII)
&& &&& &&& &&& &&& &tempString += & &;
&& &&& &&& &&& &// 判断是否为水平制表符
&& &&& &&& &&& &else if (c == TABULATION_ASCII)
&& &&& &&& &&& &&& &tempString += & & &&;
&& &&& &&& &&& &// 比较前后2个字符是否具有相同的格式
&& &&& &&& &&& &boolean flag = compareCharStyle(cr, cr2);
&& &&& &&& &&& &if (flag)
&& &&& &&& &&& &&& &tempString += cr.text();
&& &&& &&& &&& &else {
&& &&& &&& &&& &&& &String fontStyle = &&span style=&#39;font-family:&#39; + cr.getFontName() + &#39;;font-size:&#39; + cr.getFontSize() / 2 + &;
&& &&& &&& &&& &&& &if (cr.isBold())
&& &&& &&& &&& &&& &&& &fontStyle += &font-weight:&;
&& &&& &&& &&& &&& &if (cr.isItalic())
&& &&& &&& &&& &&& &&& &fontStyle += &font-style:&;
&& &&& &&& &&& &&& &htmlText += fontS
&& &&& &&& &&& &&& &if (cr.isBold())
&& &&& &&& &&& &&& &&& &fontStyle += &font-weight:&;
&& &&& &&& &&& &&& &if (cr.isItalic())
&& &&& &&& &&& &&& &&& &fontStyle += &font-style:&;
&& &&& &&& &&& &&& &htmlText += fontS
&& &&& &&& &&& &&& &tempString = &&;
&& &&& &&& &&& &}
&& &&& &&& &}
&& &&& &htmlText += tempString + &&/body&&/html&&;
&& &&& &writeFile(htmlText);
&& & * 读写文档中的表格
&& & * @param pTable
&& & * @param cr
&& & * @throws Exception
&& &public static void readTable(TableIterator it, Range rangetbl)
&& &&& &&& &throws Exception {
&& &&& &htmlTextTbl = &&;
&& &&& &// 迭代文档中的表格
&& &&& &counter = -1;
&& &&& &while (it.hasNext()) {
&& &&& &&& &tblExist =
&& &&& &&& &htmlTextTbl = &&;
&& &&& &&& &Table tb = (Table) it.next();
&& &&& &&& &beginPosi = tb.getStartOffset();
&& &&& &&& &endPosi = tb.getEndOffset();
&& &&& &&& &counter = counter + 1;
&& &&& &&& &// 迭代行,默认从0开始
&& &&& &&& &beginArray[counter] = beginP
&& &&& &&& &endArray[counter] = endP
&& &&& &&& &htmlTextTbl += &&table border&&;
&& &&& &&& &for (int i = 0; i & tb.numRows(); i++) {
&& &&& &&& &&& &TableRow tr = tb.getRow(i);
&& &&& &&& &&& &htmlTextTbl += &&tr&&;
&& &&& &&& &&& &// 迭代列,默认从0开始
&& &&& &&& &&& &for (int j = 0; j & tr.numCells(); j++) {
&& &&& &&& &&& &&& &TableCell td = tr.getCell(j);// 取得单元格
&& &&& &&& &&& &&& &int cellWidth = td.getWidth();
&& &&& &&& &&& &&& &// 取得单元格的内容
&& &&& &&& &&& &&& &for (int k = 0; k & td.numParagraphs(); k++) {
&& &&& &&& &&& &&& &&& &Paragraph para = td.getParagraph(k);
&& &&& &&& &&& &&& &&& &String s = para.text().toString().trim();
&& &&& &&& &&& &&& &&& &if (s == &&) {
&& &&& &&& &&& &&& &&& &&& &s = & &;
&& &&& &&& &&& &&& &&& &}
&& &&& &&& &&& &&& &&& &htmlTextTbl += &&td width=& + cellWidth + &&& + s
&& &&& &&& &&& &&& &&& &&& &&& &+ &&/td&&;
&& &&& &&& &&& &&& &}
&& &&& &&& &&& &}
&& &&& &&& &}
&& &&& &&& &htmlTextTbl += &&/table&&;
&& &&& &&& &htmlTextArray[counter] = htmlTextT
&& & * 读写文档中的图片
&& & * @param pTable
&& & * @param cr
&& & * @throws Exception
&& &public static void readPicture(PicturesTable pTable, CharacterRun cr)
&& &&& &&& &throws Exception {
&& &&& &// 提取图片
&& &&& &Picture pic = pTable.extractPicture(cr, false);
&& &&& &// 返回POI建议的图片文件名
&& &&& &String afileName = pic.suggestFullFileName();
&& &&& &File file =
&& &&& &if (StringUtilx.isNotEmpty(afileName)) {
&& &&& &&& &file = new File(&c://test& + File.separator + afileName);
&& &&& &if (file != null) {
&& &&& &&& &if (!file.exists()) {
&& &&& &&& &&& &file.createNewFile();
&& &&& &&& &}
&& &&& &&& &OutputStream out = new FileOutputStream(file);
&& &&& &&& &pic.writeImageContent(out);
&& &&& &&& &htmlText += &&img src=&#39;&#39;/&&;
&& &public static boolean compareCharStyle(CharacterRun cr1, CharacterRun cr2) {
&& &&& &boolean flag =
&& &&& &if (cr1.isBold() == cr2.isBold() && cr1.isItalic() == cr2.isItalic()
&& &&& &&& &&& &&& cr1.getFontName().equals(cr2.getFontName())
&& &&& &&& &&& &&& cr1.getFontSize() == cr2.getFontSize()) {
&& &&& &&& &flag =
&& & * 写文件
&& & * @param s
&& &public static void writeFile(String s) {
&& &&& &FileOutputStream fos =
&& &&& &BufferedWriter bw =
&& &&& &try {
&& &&& &&& &File file = new File(&c://abc.html&);
&& &&& &&& &fos = new FileOutputStream(file);
&& &&& &&& &bw = new BufferedWriter(new OutputStreamWriter(fos));
&& &&& &&& &bw.write(s);
&& &&& &} catch (FileNotFoundException fnfe) {
&& &&& &&& &fnfe.printStackTrace();
&& &&& &} catch (IOException ioe) {
&& &&& &&& &ioe.printStackTrace();
&& &&& &} finally {
&& &&& &&& &try {
&& &&& &&& &&& &if (bw != null)
&& &&& &&& &&& &&& &bw.close();
&& &&& &&& &&& &if (fos != null)
&& &&& &&& &&& &&& &fos.close();
&& &&& &&& &} catch (IOException ie) {
&& &&& &&& &}
之前有人问过类似的问题了。
暂无贡献等级
暂无贡献等级
暂无贡献等级
暂无贡献等级
暂无贡献等级
扫描二维码关注最代码为好友"/>扫描二维码关注最代码为好友

我要回帖

更多关于 apache poi 的文章

 

随机推荐