当前位置:   article > 正文

在无字体时使用word样式,并设置字体样式_xwpfstyles

xwpfstyles

1.引用依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>4.1.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>4.1.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>poi-ooxml-schemas</artifactId>
  14. <version>4.1.2</version>
  15. </dependency>

2. 引用word样式

2.1加载模板 获取word模板样式

  1. DefaultResourceLoader rl = new DefaultResourceLoader();
  2. //加载文件
  3. Resource rs = rl.getResource("word的文件路径");
  4. //加载文件流,创建XWPFDocument 对象
  5. XWPFDocument temp = new XWPFDocument(rs.getInputStream());
  6. //获取模板的样式
  7. CTStyles templateStyle = temp.getStyle();

3.设置word的样式

3.1将模板的样式加载到要设置的word上

  1. //inputStream 为要设置样式的word文件流
  2. // 要设置的word文档对象
  3. XWPFDocument doc = new XWPFDocument(inputStream);
  4. //将模板的样式赋值到要设置样式的word上,这样doc则可以设置word里的样式:包括字体样式等
  5. XWPFStyles styles = doc.createStyles();
  6. styles.setStyles(templateStyle );

3.1.1设置word纸张大小和方向

  1. /**
  2. *纸张大小解析:
  3. * Letter:612*792
  4. * LetterSmall:612*792
  5. * Tabloid:792*1224
  6. * Ledger:1224*792
  7. * Legal:612*1008
  8. * Statement:369*612
  9. * Executive:540*720
  10. * A0:2384*3371
  11. * A1:1685*2384
  12. * A2:1190*1684
  13. * A3:842*1190
  14. * A4:595*842
  15. * A4Small:595*842
  16. * A5:420*595
  17. * B4:729*1032
  18. * B5:516*729
  19. * Folio:612*936
  20. * Quarto:610*780
  21. * 宽和高乘以20
  22. * eg: A4 595*20=11900 842*20=16840
  23. * 当宽小于长为纵向,否则为横向
  24. */
  25. CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
  26. CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();
  27. pgsz.setW(new BigInteger(11900) );
  28. pgsz.setH(new BigInteger(16840));
  29. pgsz.setOrient(STPageOrientation.PORTRAIT);

3.2设置样式

  1. //获取段落
  2. List<XWPFParagraph> paragraphs = doc.getParagraphs();
  3. XWPFParagraph ph=paragraphs.get(0);
  4. //设置行间距
  5. ph.setSpacingBetween(1.15D)
  6. //设置首行缩进
  7. ph.setIndentationFirstLine(500)
  8. //设置对齐方式
  9. ph.setAlignment(ParagraphAlignment.LEFT)
  10. List<XWPFRun> runs = ph.getRuns();
  11. XWPFRun run = runs.get(0);
  12. //设置字体大小
  13. run.setFontSize(15);
  14. CTRPr rp;
  15. if(run.getCTR().isSetRPr()){
  16. rp= run.getCTR().getRPr();
  17. }else{
  18. rp= run.getCTR().addNewRPr()
  19. }
  20. CTFonts fonts;
  21. if(rp.isSetRFonts()){
  22. fonts=rp.getRFonts();
  23. }else{
  24. fonts= rp.addNewRFonts();
  25. }
  26. //设置颜色
  27. rp.setColor("");
  28. //改变数字或者英文字体
  29. fonts.setAscii("Arial");
  30. //改变中文字体
  31. fonts.setEastAsia("新宋体");
  32. fonts.setHAnsi("仿宋");

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/709522
推荐阅读
相关标签
  

闽ICP备14008679号