XWPFDocument创建和读取Office Word文档基础篇(一)
- 表格的一格相当于一个完整的docx文档,只是没有页眉和页脚。里面可以有表格,使用xwpfTableCell.getTables()获取,and so on
 - 在poi文档中段落和表格是完全分开的,如果在两个段落中有一个表格,在poi中是没办法确定表格在段落中间的。(当然除非你本来知道了,这句是废话)。只有文档的格式固定,才能正确的得到文档的结构
 
InputStream is = new FileInputStream("D:\\table.docx");
XWPFDocument doc = new XWPFDocument(is);
List<XWPFParagraph> paras = doc.getParagraphs(); 
for (XWPFParagraph para : paras) {
    //当前段落的属性
//CTPPr pr = para.getCTP().getPPr();
System.out.println(para.getText());
} 
List<XWPFTable> tables = doc.getTables();
List<XWPFTableRow> rows;
List<XWPFTableCell> cells; for (XWPFTable table : tables) {
//表格属性
CTTblPr pr = table.getCTTbl().getTblPr();
//获取表格对应的行
rows = table.getRows();
for (XWPFTableRow row : rows) {
//获取行对应的单元格
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
System.out.println(cell.getText());;
}
}
}
XWPFDocument doc = new XWPFDocument();
//创建一个段落
XWPFParagraph para = doc.createParagraph(); //一个XWPFRun代表具有相同属性的一个区域:一段文本
XWPFRun run = para.createRun();
run.setBold(true); //加粗
run.setText("加粗的内容");
run = para.createRun();
run.setColor("FF0000");
run.setText("红色的字。");
OutputStream os = new FileOutputStream("D:\\simpleWrite.docx");
//把doc输出到输出流
doc.write(os);
this.close(os);
//XWPFDocument doc = new XWPFDocument();
//创建一个5行5列的表格
XWPFTable table = doc.createTable(5, 5);
//这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到,但通过row新增的就可以。
//table.addNewCol(); //给表格增加一列,变成6列
table.createRow(); //给表格新增一行,变成6行
List<XWPFTableRow> rows = table.getRows();
//表格属性
CTTblPr tablePr = table.getCTTbl().addNewTblPr();
//表格宽度
CTTblWidth width = tablePr.addNewTblW();
width.setW(BigInteger.valueOf(8000));
XWPFTableRow row;
List<XWPFTableCell> cells;
XWPFTableCell cell;
int rowSize = rows.size();
int cellSize;
for (int i=0; i<rowSize; i++) {
row = rows.get(i);
//新增单元格
row.addNewTableCell();
//设置行的高度
row.setHeight(500);
//行属性
//CTTrPr rowPr = row.getCtRow().addNewTrPr();
//这种方式是可以获取到新增的cell的。
//List<CTTc> list = row.getCtRow().getTcList();
cells = row.getTableCells();
cellSize = cells.size();
for (int j=0; j<cellSize; j++) {
cell = cells.get(j);
if ((i+j)%2==0) {
//设置单元格的颜色
cell.setColor("ff0000"); //红色
} else {
cell.setColor("0000ff"); //蓝色
}
//单元格属性
CTTcPr cellPr = cell.getCTTc().addNewTcPr();
cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
if (j == 3) {
//设置宽度
cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
}
cell.setText(i + ", " + j);
}
}
//文件不存在时会自动创建
OutputStream os = new FileOutputStream("D:\\table.docx");
//写入文件
doc.write(os);
this.close(os);
/**
* 替换段落里面的变量
* @param para 要替换的段落
* @param params 参数
*/
private void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
List<XWPFRun> runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
for (int i=0; i<runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
matcher = this.matcher(runText);
if (matcher.find()) {
while ((matcher = this.matcher(runText)).find()) {
runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
}
//直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
//所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
para.removeRun(i);
para.insertNewRun(i).setText(runText);
}
}
}
}
String path ="D://abc.docx";
File file = new File(path);
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument document = new XWPFDocument(fis);
XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(document);
String text = xwpfWordExtractor.getText();
System.out.println(text);
List<XWPFPictureData> picList = document.getAllPictures();
for (XWPFPictureData pic : picList) {
System.out.println(pic.getPictureType() + file.separator + pic.suggestFileExtension()
+file.separator+pic.getFileName());
byte[] bytev = pic.getData();
FileOutputStream fos = new FileOutputStream("D:\\abc\\docxImage\\"+pic.getFileName());
fos.write(bytev);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 自定义样式方式写word,参考statckoverflow的源码
*
* @throws IOException
*/
public static void writeSimpleDocxFile() throws IOException {
XWPFDocument docxDocument = new XWPFDocument(); // 老外自定义了一个名字,中文版的最好还是按照word给的标题名来,否则级别上可能会乱
addCustomHeadingStyle(docxDocument, "标题 1", 1);
addCustomHeadingStyle(docxDocument, "标题 2", 2); // 标题1
XWPFParagraph paragraph = docxDocument.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("标题 1");
paragraph.setStyle("标题 1"); // 标题2
XWPFParagraph paragraph2 = docxDocument.createParagraph();
XWPFRun run2 = paragraph2.createRun();
run2.setText("标题 2");
paragraph2.setStyle("标题 2"); // 正文
XWPFParagraph paragraphX = docxDocument.createParagraph();
XWPFRun runX = paragraphX.createRun();
runX.setText("正文");
// word写入到文件
FileOutputStream fos = new FileOutputStream("D:/myDoc2.docx");
docxDocument.write(fos);
fos.close();
} /**
* 增加自定义标题样式。这里用的是stackoverflow的源码
*
* @param docxDocument 目标文档
* @param strStyleId 样式名称
* @param headingLevel 样式级别
*/
private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, int headingLevel) { CTStyle ctStyle = CTStyle.Factory.newInstance();
ctStyle.setStyleId(strStyleId); CTString styleName = CTString.Factory.newInstance();
styleName.setVal(strStyleId);
ctStyle.setName(styleName); CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
indentNumber.setVal(BigInteger.valueOf(headingLevel)); // lower number > style is more prominent in the formats bar
ctStyle.setUiPriority(indentNumber); CTOnOff onoffnull = CTOnOff.Factory.newInstance();
ctStyle.setUnhideWhenUsed(onoffnull); // style shows up in the formats bar
ctStyle.setQFormat(onoffnull); // style defines a heading of the given level
CTPPr ppr = CTPPr.Factory.newInstance();
ppr.setOutlineLvl(indentNumber);
ctStyle.setPPr(ppr); XWPFStyle style = new XWPFStyle(ctStyle); // is a null op if already defined
XWPFStyles styles = docxDocument.createStyles(); style.setType(STStyleType.PARAGRAPH);
styles.addStyle(style); }
XWPFDocument创建和读取Office Word文档基础篇(一)的更多相关文章
- java 使用 POI 操作 XWPFDocumen 创建和读取 Office Word 文档基础篇
		
注:有不正确的地方还望大神能够指出,抱拳了 老铁! 参考 API:http://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFDoc ...
 - 使用ABAP编程实现对微软Office Word文档的操作
		
SAP ABAP里提供了一个标准的类CL_DOCX_DOCUMENT,提供了本地以".docx"结尾的微软Office word文档的读和写操作. 本文介绍了ABAP类CL_DOC ...
 - 新建 Microsoft Office Word 文档 来源:牛客网
		
题目 链接:https://ac.nowcoder.com/acm/contest/28886/1015 来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32768K,其 ...
 - 基于springboot的freemarker创建指定格式的word文档
		
在web或其他应用中,经常我们需要导出或者预览word文档,比较实际的例子有招聘网站上预览或者导出个人简历,使用POI导出excel会非常的方便,但是如果想导出word,由于其格式控制非常复杂,故而使 ...
 - 用注册表清除Office Word文档杀手病毒
		
不久前,笔者打开word文件时遇到了一件离奇的怪事,常用的Word文件怎么也打不开,总是出现提示框:"版本冲突:无法打开高版本的word文档".再仔细查看,文件夹里竟然有两个名字一 ...
 - c#写word文档基础操作(自己控制样式)
		
下面一个函数,建立一个Word 文档,添加页眉.页脚,在内容中两个不同字体的Hello!!! 来自 <http://bbs.csdn.net/topics/340041961> pub ...
 - Mongoose学习参考文档——基础篇
		
Mongoose学习参考文档 前言:本学习参考文档仅供参考,如有问题,师请雅正 一.快速通道 1.1 名词解释 Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model ...
 - Ehcache 3.7文档—基础篇—XML Configuration
		
你可以使用xml配置创建CacheManager,根据这个schema definition ( http://www.ehcache.org/documentation/3.7/xsds.html# ...
 - Ehcache 3.7文档—基础篇—JCache aka JSR-107
		
一. 概述JCache Java临时缓存API(JSR-107),也被称为JCache,它是一个规范在javax.cache.API中定义的.该规范是在Java Community Process下开 ...
 
随机推荐
- LeetCode-Maximum Subarray[dp]
			
Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which ...
 - 浅析python 的import 模块(转)
			
摘要: 学习python有几天了,对import一直不是很清楚,和C里面的include是否一样,重复引入有问题么?搜索路径是怎样的?整理解决下我的疑问. 一 模块的搜索路径 模块的搜索路径都放在了s ...
 - HTML5 开发APP(头部和底部选项卡)
			
我们开发app有一定固定的样式,比如头部和底部选项卡部分就是公共部分就比如我在做的app进来的主页面就像图片显示的那样 我们该怎么实现呢,实现我们应该建一个主页面index.html,然后建五个子页面 ...
 - 【设计模式】Bridge模式(桥接模式)
			
最近的一次面试中,被问到桥接模式,以前呢并没有很仔细的研究过这个设计模式,借此机会剖析一下. 先给出自己对这个模式理解后的源码: interface A{ void methodA(); } inte ...
 - 网关(Gatesvr) 设计(1)
			
Gate解决的问题: 1.用户在服务端的实例可以在不同的进程中,也可以移动到同一个进程中.2.用户只需要与服务端建立有限条连接,即可以访问到任意服务进程.这个连接的数量不会随服务进程的数量增长而线性增 ...
 - Scrapy模拟登录知乎
			
建立项目 scrapy startproject zhihu_login scrapy genspider zhihu www.zhihu.com 编写spider 知乎的登录页url是http:// ...
 - hdu  6093---Rikka with Number(计数)
			
题目链接 Problem Description As we know, Rikka is poor at math. Yuta is worrying about this situation, s ...
 - 模板 mú bǎn
			
链式前向星 #include<string.h> #define MAX 10000 struct node { int to,nex,wei; }edge[MAX*+]; ],cnt; ...
 - hdu--1316--How Many Fibs?(java大数)
			
How Many Fibs? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...
 - 身在魔都的她,该不该继续"坚持"前端开发?
			
一 这个女孩儿,是我很好很好很好的一位朋友,也是中学的同学,去年从她的本科大学毕业,毕业后由于没找到合适的工作而选择去培训机构培训了比较火爆的前端开发,之后去了上海找工作,但是由于一些原因在从上一家公 ...