赞
踩
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>4.1.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>4.1.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml-schemas</artifactId>
- <version>4.1.2</version>
- </dependency>
- DefaultResourceLoader rl = new DefaultResourceLoader();
- //加载文件
- Resource rs = rl.getResource("word的文件路径");
- //加载文件流,创建XWPFDocument 对象
- XWPFDocument temp = new XWPFDocument(rs.getInputStream());
- //获取模板的样式
- CTStyles templateStyle = temp.getStyle();
- //inputStream 为要设置样式的word文件流
- // 要设置的word文档对象
- XWPFDocument doc = new XWPFDocument(inputStream);
- //将模板的样式赋值到要设置样式的word上,这样doc则可以设置word里的样式:包括字体样式等
- XWPFStyles styles = doc.createStyles();
- styles.setStyles(templateStyle );
3.1.1设置word纸张大小和方向
-
- /**
- *纸张大小解析:
- * Letter:612*792
- * LetterSmall:612*792
- * Tabloid:792*1224
- * Ledger:1224*792
- * Legal:612*1008
- * Statement:369*612
- * Executive:540*720
- * A0:2384*3371
- * A1:1685*2384
- * A2:1190*1684
- * A3:842*1190
- * A4:595*842
- * A4Small:595*842
- * A5:420*595
- * B4:729*1032
- * B5:516*729
- * Folio:612*936
- * Quarto:610*780
- * 宽和高乘以20
- * eg: A4 595*20=11900 842*20=16840
- * 当宽小于长为纵向,否则为横向
- */
-
- CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
- CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();
- pgsz.setW(new BigInteger(11900) );
- pgsz.setH(new BigInteger(16840));
- pgsz.setOrient(STPageOrientation.PORTRAIT);

- //获取段落
- List<XWPFParagraph> paragraphs = doc.getParagraphs();
- XWPFParagraph ph=paragraphs.get(0);
- //设置行间距
- ph.setSpacingBetween(1.15D)
- //设置首行缩进
- ph.setIndentationFirstLine(500)
- //设置对齐方式
- ph.setAlignment(ParagraphAlignment.LEFT)
- List<XWPFRun> runs = ph.getRuns();
- XWPFRun run = runs.get(0);
- //设置字体大小
- run.setFontSize(15);
- CTRPr rp;
- if(run.getCTR().isSetRPr()){
- rp= run.getCTR().getRPr();
- }else{
- rp= run.getCTR().addNewRPr()
- }
- CTFonts fonts;
- if(rp.isSetRFonts()){
- fonts=rp.getRFonts();
- }else{
- fonts= rp.addNewRFonts();
- }
- //设置颜色
- rp.setColor("");
- //改变数字或者英文字体
- fonts.setAscii("Arial");
- //改变中文字体
- fonts.setEastAsia("新宋体");
- fonts.setHAnsi("仿宋");

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。