Java 操作World表格

本文介绍如何使用Java进行Word文档的操作,包括创建表格、设置表格样式、替换段落内容及抽取图片等。文中还提供了多级标题的创建方法以及自定义样式的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个表格

//XWPFDocument doc = new XWPFDocument();//创建一个5行5列的表格

XWPFTable table = doc.createTable(5, 5);//这里增加的列原本初始化创建的那5行在通过getTableCells()方法获取时获取不到,但通过row新增的就可以。//table.addNewCol();//给表格增加一列,变成6列

table.createRow(); //给表格新增一行,变成6行

List rows =table.getRows();//表格属性

CTTblPr tablePr =table.getCTTbl().addNewTblPr();//表格宽度

CTTblWidth width =tablePr.addNewTblW();

width.setW(BigInteger.valueOf(8000));

XWPFTableRow row;

Listcells;

XWPFTableCell cell;int rowSize =rows.size();intcellSize;for (int i=0; i

row=rows.get(i);//新增单元格

row.addNewTableCell();//设置行的高度

row.setHeight(500);//行属性//CTTrPr rowPr = row.getCtRow().addNewTrPr();//这种方式是可以获取到新增的cell的。//List list = row.getCtRow().getTcList();

cells =row.getTableCells();

cellSize=cells.size();for (int j=0; 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);

段落内容替换

/*** 替换段落里面的变量

*@parampara 要替换的段落

*@paramparams 参数*/

private void replaceInPara(XWPFParagraph para, Mapparams) {

Listruns;

Matcher matcher;if (this.matcher(para.getParagraphText()).find()) {

runs=para.getRuns();for (int i=0; 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);

}

}

}

}

直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。

//抽取 word docx文件中的图片

String path ="D://abc.docx";

File file= newFile(path);try{

FileInputStream fis= newFileInputStream(file);

XWPFDocument document= newXWPFDocument(fis);

XWPFWordExtractor xwpfWordExtractor= newXWPFWordExtractor(document);

String text=xwpfWordExtractor.getText();

System.out.println(text);

List 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的源码

*

*@throwsIOException*/

public static void writeSimpleDocxFile() throwsIOException {

XWPFDocument docxDocument= newXWPFDocument();//老外自定义了一个名字,中文版的最好还是按照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的源码

*

*@paramdocxDocument 目标文档

*@paramstrStyleId 样式名称

*@paramheadingLevel 样式级别*/

private static void addCustomHeadingStyle(XWPFDocument docxDocument, String strStyleId, intheadingLevel) {

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= newXWPFStyle(ctStyle);//is a null op if already defined

XWPFStyles styles =docxDocument.createStyles();

style.setType(STStyleType.PARAGRAPH);

styles.addStyle(style);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值