当前位置:   article > 正文

Java使用spire.doc操作word文档docx(合并、插入文字图片和表格、替换书签、修改样式、操作表格、页眉、页脚、首行缩进)_spire文档

spire文档

一、引入依赖

  1. <dependency>
  2. <groupId>e-iceblue</groupId>
  3. <artifactId>spire.office</artifactId>
  4. <version>7.5.4</version>
  5. </dependency>

二、word操作

1、合并word文档

  1. import com.spire.doc.Document;
  2. import com.spire.doc.DocumentObject;
  3. import com.spire.doc.FileFormat;
  4. import com.spire.doc.Section;
  5. /**
  6. * 合并Word文档
  7. *
  8. * @Description
  9. * @Author ROC_WL
  10. * @Date 2024/3/8
  11. **/
  12. public class MergerDocxTest {
  13. public static void main(String[] args) {
  14. //创建document对象
  15. Document document = new Document("D:\\temp\\document-blank.docx");//读取一个空的Word文档
  16. //加载一个需要写入的Word文档
  17. Document doc1 = new Document("D:\\temp\\document1.docx");
  18. for (int i = 0; i < doc1.getSections().getCount(); i++) {
  19. Section s = doc1.getSections().get(i);
  20. for (int j = 0; j < s.getBody().getChildObjects().getCount(); j++) {
  21. //获取文档中的段落和表格
  22. DocumentObject obj = s.getBody().getChildObjects().get(j);
  23. //将文档中的段落和表格插入到新的文档中
  24. document.getLastSection().getBody().getChildObjects().add(obj.deepClone());
  25. }
  26. }
  27. //循环写入
  28. for (int x = 0; x < 2; x++) {
  29. Document doc2 = new Document("D:\\temp\\document2.docx");
  30. for (int i = 0; i < doc2.getSections().getCount(); i++) {
  31. Section s = doc2.getSections().get(i);
  32. for (int j = 0; j < s.getBody().getChildObjects().getCount(); j++) {
  33. DocumentObject obj = s.getBody().getChildObjects().get(j);
  34. document.getLastSection().getBody().getChildObjects().add(obj.deepClone());
  35. }
  36. }
  37. }
  38. //保存文档
  39. document.saveToFile("D:\\temp\\mergerDocx.docx", FileFormat.Docx_2013);
  40. }
  41. }

 

2、插入文字、图片、表格、富文本

  1. import com.example.utils.DocxUtil;
  2. import com.spire.doc.*;
  3. import com.spire.doc.documents.*;
  4. import com.spire.doc.fields.DocPicture;
  5. import java.awt.*;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. /**
  9. * TODO
  10. *
  11. * @Description
  12. * @Author WL
  13. * @Date 2024/2/28
  14. **/
  15. public class DocxAddParagraphTest {
  16. public static void main(String[] args) {
  17. //创建document对象
  18. Document document = new Document("D:\\temp\\document-blank.docx");
  19. //获取最后一个section
  20. Section newSec = document.getLastSection();
  21. //添加文本
  22. Paragraph textParagtaph = newSec.addParagraph();
  23. //设置文本格式
  24. ParagraphStyle styleContent = new ParagraphStyle(document);
  25. styleContent.setName("codeStyle");
  26. styleContent.getCharacterFormat().setFontName("宋体");
  27. styleContent.getCharacterFormat().setFontSize(10f);
  28. styleContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
  29. document.getStyles().add(styleContent);
  30. textParagtaph.applyStyle("codeStyle");
  31. textParagtaph.appendText("第01号");
  32. Paragraph text1Paragtaph = newSec.addParagraph();
  33. //设置文本格式
  34. ParagraphStyle styleTitle = new ParagraphStyle(document);
  35. //设置样式名称
  36. styleTitle.setName("titleStyle");
  37. //设置字体
  38. styleTitle.getCharacterFormat().setFontName("宋体");
  39. //设置字体大小
  40. styleTitle.getCharacterFormat().setFontSize(20f);
  41. //设置文本颜色
  42. styleTitle.getCharacterFormat().setTextColor(Color.CYAN);
  43. //设置文本居中
  44. styleTitle.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  45. //添加样式到文档
  46. document.getStyles().add(styleTitle);
  47. //应用样式
  48. text1Paragtaph.applyStyle("titleStyle");
  49. //添加文本
  50. text1Paragtaph.appendText("关于******公告");
  51. //添加文本
  52. Paragraph textPeoParagtaph = newSec.addParagraph();
  53. //设置文本格式
  54. ParagraphStyle stylePeoContent = new ParagraphStyle(document);
  55. stylePeoContent.setName("peoStyle");
  56. stylePeoContent.getCharacterFormat().setFontName("宋体");
  57. stylePeoContent.getCharacterFormat().setFontSize(12f);
  58. stylePeoContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
  59. document.getStyles().add(stylePeoContent);
  60. textPeoParagtaph.applyStyle("peoStyle");
  61. textPeoParagtaph.appendText("姓名:姜XX\t\t\t手机号码:13866669999");
  62. //添加文本
  63. Paragraph textAddParagtaph = newSec.addParagraph();
  64. //设置文本格式
  65. ParagraphStyle styleAddContent = new ParagraphStyle(document);
  66. styleAddContent.setName("addStyle");
  67. styleAddContent.getCharacterFormat().setFontName("宋体");
  68. styleAddContent.getCharacterFormat().setFontSize(12f);
  69. styleAddContent.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
  70. document.getStyles().add(styleAddContent);
  71. textAddParagtaph.applyStyle("addStyle");
  72. textAddParagtaph.getFormat().setFirstLineIndent(30f);
  73. textAddParagtaph.appendText("联系地址:湖北武汉");
  74. //添加表格
  75. List<String> headerList = new ArrayList<>();
  76. headerList.add("姓名");
  77. headerList.add("电话");
  78. headerList.add("地址");
  79. List<List<Object>> dataList = new ArrayList<>();
  80. List<Object> data1 = new ArrayList<>();
  81. data1.add("姜XX");
  82. data1.add("18899996666");
  83. data1.add("浙江");
  84. dataList.add(data1);
  85. List<Object> data2 = new ArrayList<>();
  86. data2.add("tj");
  87. data2.add("15549490011");
  88. data2.add("杭州");
  89. dataList.add(data2);
  90. List<Object> data3 = new ArrayList<>();
  91. data3.add("赵XX");
  92. data3.add("135****713");
  93. data3.add("武汉");
  94. dataList.add(data3);
  95. String tableTitle = "表格标题";
  96. DocxUtil.createTable(newSec, headerList, dataList, tableTitle);
  97. //添加图片
  98. // 创建 DocPicture 类的对象
  99. DocPicture picture = new DocPicture(document);
  100. // 从磁盘加载图片
  101. String images = "D:\\temp\\123.jpg";
  102. picture.loadImage(images);
  103. // 设置图片大小
  104. picture.setWidth(180); //示例:80
  105. picture.setHeight(180);//示例:50
  106. picture.setHorizontalPosition(110); //示例:110.0F 水平位置
  107. picture.setVerticalPosition(220); //示例:110.0F 垂直位置
  108. Paragraph picParagraph = newSec.addParagraph();
  109. picParagraph.getChildObjects().add(picture);
  110. //添加图片
  111. // 创建 DocPicture 类的对象
  112. DocPicture picture1 = new DocPicture(document);
  113. // 从磁盘加载图片
  114. String images1 = "D:\\temp\\321.jpg";
  115. picture1.loadImage(images1);
  116. // 设置图片大小
  117. picture1.setWidth(500); //示例:80
  118. picture1.setHeight(180);//示例:50
  119. picture1.setHorizontalPosition(110); //示例:110.0F 水平位置
  120. picture1.setVerticalPosition(220); //示例:110.0F 垂直位置
  121. Paragraph picParagraph1 = newSec.addParagraph();
  122. picParagraph1.getChildObjects().add(picture1);
  123. //添加富文本
  124. Paragraph tempSectionContentParagraph = newSec.addParagraph();
  125. String htmlContent = "<p>Spire.Doc for Java 是一款专业的 Java Word 组件,开发人员使用它可以轻松地将 Word 文档创建、读取、编辑、转换和打印等功能集成到自己的 Java 应用程序中。作为一款完全独立的组件,Spire.Doc for Java 的运行环境无需安装 Microsoft Office。</p>
  126. <p>Spire.Doc for Java 能执行多种 Word 文档处理任务,包括生成、读取、转换和打印 Word 文档,插入图片,添加页眉和页脚,创建表格,添加表单域和邮件合并域,添加书签,添加文本和图片水印,设置背景颜色和背景图片,添加脚注和尾注,添加超链接,加密和解密 Word 文档,添加批注,添加形状等。</p>
  127. <p><img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAAAXNSR0IArs4c6QAABWVJREFUeAHtnF9oW1Ucx3/nJumWZNXRqUh7W+PYFFa6NKAgKLVMHKgg+jARYYgMfaqwl3V7W/cidj46fVBERBHZi3tQx8ANGSKIQpqWPYyOLV1vowirxTaJS5N79vvdQdaO3Oacc+9NbsLJ0/3z/f3O9/fJ+XPvzW0B9EcT0AQ0AU1AE9AENAFNQBNoMwHW5vY3NZ8biJucwwQw9jJw/rhzkrEbuP0TY3AmvVS2NgW0eCc0sGbM+ASCOg0c4g0ZMCgDZ8cyhdInDc+34GAoYM30xz/kAMdF6kXD06OF8gkRrd8aw++EsvmyZmJKFBTlJi3FyLbjh76tPStrJifBtqeVCjGM4xmreFopVjGobbCcOcqGjxV9O2HMgPdHrfIZLzlkYtsCK2cmjnCbf45DylP7GMyZwd5NW6UvZIpW1Xoyq9LorJl8y7btrxGUL/MlFmAbhnF4v1X8VsWPTExLYeHQe53bcBYNRmVMCmirOCTfwCH5vYBWWdIyWLNm4iWb83N4LdWj7HaLQLxorRiMvbbfKp3fQubpVEtg5QZ2HOBQ+xFBbffktkkwAvufQeSV9NLapSZSpdOBw8oO9T7LqtULOEcllRxKBmFBxQhED44UVn+TDG0qDxTW3GDiqWoNLuKi9UBTJ74K2H/RCLwwslj608+0gcHCVW8E56hfOOd9fhoWzcUYW8Y5bBxXyTnRmGa6QGDl+nufxDnqMgf+SDMDQZ5nwP7BOWwsXVi96kc7vlzrbDQyO/Tgbs5qF9sNijyRB/JCnjZ6VN32tWfN9fcN1qCMPQpSqoaCiMMi8xGIj40Ulhe95PcN1pVU8tHKun0Zv869XgwFFstgvidmjA3ni3+rtuHLMLz6RO9D6xX+c2hBER38EskjeVWF5blnZVM7d7L1yiVc9TKqJloZh6tklsd6DmTyKyuy7XrqWVeGH96BoM53CiiCQ17JM3lvGaxF04xXVtZ+wMafkW203XryTN6pBhkvSj1rfs+ebbfs5XM4Dzwv01iotOidaqBaRH1Jw+Lj49G1cuEsXsMcFG0krDqqwakFaxLxKAWLHzoUyc3//g0O/FdFkneEBmuhmqi2Zn6FV0Mc52zGTH6JoN5ulrQjzzP21ahVfAdXS7ymbvwR7lm5gcQHXQuK2GAncGpszMk5KtSzZoZ6n4NqlW5jhPRbtBfqU1gch2h0bPTm6q+NjIr1rFp1ottBERynRqy1ESg6JgYL2ItuCbrvuHutgrBEoXYFOlcmric2l80vbN7v5j33WoVgxWLGUZzar3UzIqc2rNGp1aVQ4dWN7qOW4dZ7+CPp0whuoJ6PQwonxlR9vwM2sOg81pCvW+WwhD/S/tEHuz4btKxy/fh9G8Kw7our7+b6Eydt4FP1Ax2wYQCbShdKp2StCg1D2aTdqtewJL5ZobttiXxKUvrZHW8OvuMMFrZKgHdtj+Gl45tBvwbg5iEUsDhj0xmrNOVmcuNxfEVyAe/jTm481qrtUAxDg7ProgXLaEVziupCAQvNyqzKMlpRDkK6sMASMksiWw6scF4RYcfBEikqKI2GJUFWw9KwJAhISHXP0rAkCEhIdc/SsCQISEh1z9KwJAhISD33LHxisCbRXiikqp49w8I/YrNCQUDGhKJnz7B6YvjSbYd9VD17hrVvofQXPumkP4vriA95Jc8qZj3DokZj27YfwydSrj8hqRgLJAY9Ol4Vk/sCa/j6vzeBG2151CtVN3p0vEoF3RP7AovSZQrFj/A9k0nsYev30odky/FkTN71qO7JN1hkgcxEo5E0/nuUTxHaNZwfbqtb8xbptE2vHKAX8uQVlDc3OloT0AQ0AU1AE+gWAncAtcuNfiX0sWkAAAAASUVORK5CYII=" alt="" width="75" height="75" /></p>";
  128. htmlContent=htmlContent+"<p>&nbsp;</p>";
  129. tempSectionContentParagraph.appendHTML(htmlContent);
  130. //添加文本
  131. Paragraph text3Paragtaph = newSec.addParagraph();
  132. ParagraphStyle styleContent3 = new ParagraphStyle(document);
  133. styleContent3.setName("codeStyle3");
  134. styleContent3.getCharacterFormat().setFontName("宋体");
  135. styleContent3.getCharacterFormat().setFontSize(15f);
  136. document.getStyles().add(styleContent3);
  137. text3Paragtaph.applyStyle("codeStyle3");
  138. text3Paragtaph.appendText("第02号");
  139. Paragraph text4Paragtaph = newSec.addParagraph();
  140. //设置文本格式
  141. ParagraphStyle styleTitle4 = new ParagraphStyle(document);
  142. styleTitle4.setName("titleStyle4");
  143. styleTitle4.getCharacterFormat().setFontName("宋体");
  144. styleTitle4.getCharacterFormat().setFontSize(25f);
  145. styleTitle4.getCharacterFormat().setTextColor(Color.ORANGE);
  146. styleTitle4.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  147. document.getStyles().add(styleTitle4);
  148. text4Paragtaph.applyStyle("titleStyle4");
  149. text4Paragtaph.appendText("关于***************************Text");
  150. DocxUtil.insertHeaderAndFooter(newSec);
  151. document.saveToFile("D:\\temp\\documentNew.docx", FileFormat.Docx_2013);
  152. }
  153. }

使用到的工具

  1. import com.spire.doc.*;
  2. import com.spire.doc.documents.*;
  3. import com.spire.doc.fields.TextRange;
  4. import java.awt.*;
  5. import java.security.Timestamp;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import java.util.List;
  9. /**
  10. * TODO
  11. *
  12. * @Description
  13. * @Author WL
  14. * @Date 2024/2/28
  15. **/
  16. public class DocxUtil {
  17. // 动态创建表格
  18. public static void createTable(Section section, List<String> header, List<List<Object>> data, String title) {
  19. //添加表格
  20. Table table = section.addTable(true);
  21. //设置表格的行数和列数
  22. table.resetCells(data.size()+ 2, header.size());
  23. //设置第一行作为表格的表头并添加数据
  24. TableRow row = table.getRows().get(1);
  25. row.isHeader(true);
  26. row.setHeight(40);
  27. row.setHeightType(TableRowHeightType.Exactly);
  28. TableRow row3 = table.getRows().get(0);
  29. row3.isHeader(true);
  30. row3.setHeight(60);
  31. row3.setHeightType(TableRowHeightType.Exactly);
  32. row3.getCells().get(0).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
  33. table.applyHorizontalMerge(0, 0, header.size() - 1);
  34. Paragraph p1 = row3.getCells().get(0).addParagraph();
  35. p1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  36. TextRange range3 = p1.appendText(title);
  37. range3.getCharacterFormat().setFontName("仿宋_GB2312");
  38. range3.getCharacterFormat().setFontSize(12f);
  39. range3.getCharacterFormat().setTextColor(Color.black);
  40. range3.getCharacterFormat().setBold(true);
  41. for (int i = 0; i < header.size(); i++) {
  42. row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
  43. Paragraph p = row.getCells().get(i).addParagraph();
  44. p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  45. TextRange range1 = p.appendText(header.get(i));
  46. range1.getCharacterFormat().setTextColor(Color.black);
  47. range1.getCharacterFormat().setFontName("仿宋_GB2312");
  48. range1.getCharacterFormat().setFontSize(12f);
  49. range1.getCharacterFormat().setBold(true);
  50. }
  51. //添加数据到剩余行
  52. try{
  53. for (int r = 0; r < data.size(); r++) {
  54. TableRow dataRow = table.getRows().get(r + 2);
  55. dataRow.setHeight(25);
  56. dataRow.setHeightType(TableRowHeightType.Exactly);
  57. dataRow.getRowFormat().setBackColor(Color.white);
  58. for (int c = 0; c < data.get(r).size(); c++) {
  59. dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
  60. String s = "";
  61. if (data.get(r).get(c) instanceof Timestamp) {
  62. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
  63. s = df.format((Timestamp) (data.get(r).get(c)));
  64. } else if (data.get(r).get(c) instanceof Date) {
  65. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
  66. s = df.format((Date) (data.get(r).get(c)));
  67. } else if (data.get(r).get(c) == null) {
  68. s = "";
  69. } else {
  70. s = data.get(r).get(c).toString();
  71. }
  72. TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(s);
  73. range2.getCharacterFormat().setFontName("仿宋_GB2312");
  74. range2.getCharacterFormat().setFontSize(10f);
  75. }
  76. }
  77. }catch (Exception e){
  78. e.getMessage();
  79. // log.info("插入数据有异常");
  80. }
  81. section.addParagraph();
  82. }
  83. //生成页眉和页脚
  84. public static void insertHeaderAndFooter(Section section) {
  85. //分别获取section的页眉页脚
  86. HeaderFooter header = section.getHeadersFooters().getHeader();
  87. HeaderFooter footer = section.getHeadersFooters().getFooter();
  88. //添加段落到页眉
  89. Paragraph headerParagraph = header.addParagraph();
  90. //添加文字到页眉的段落
  91. TextRange text = headerParagraph.appendText("页眉测试");
  92. text.getCharacterFormat().setFontName("仿宋_GB2312");
  93. text.getCharacterFormat().setFontSize(10);
  94. text.getCharacterFormat().setItalic(true);
  95. headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
  96. //设置页眉段落的底部边线样式
  97. headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single);
  98. headerParagraph.getFormat().getBorders().getBottom().setLineWidth(1f);
  99. //添加段落到页脚
  100. Paragraph footerParagraph = footer.addParagraph();
  101. //添加Field_Page和Field_Num_Pages域到页脚段落,用于显示当前页码和总页数
  102. footerParagraph.appendField("page number", FieldType.Field_Page);
  103. footerParagraph.appendText("/");
  104. footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages);
  105. footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
  106. //设置页脚段落的顶部边线样式
  107. footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single);
  108. footerParagraph.getFormat().getBorders().getTop().setLineWidth(1f);
  109. }
  110. }

附上整理过的demo

  1. import com.spire.doc.*;
  2. import com.spire.doc.collections.*;
  3. import com.spire.doc.documents.*;
  4. import com.spire.doc.fields.DocPicture;
  5. import com.spire.doc.fields.TextRange;
  6. import com.spire.doc.formatting.ParagraphFormat;
  7. import java.awt.*;
  8. import java.awt.image.BufferedImage;
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. import java.io.IOException;
  12. import java.util.List;
  13. import java.util.regex.Pattern;
  14. /**
  15. * spire操作docx
  16. *
  17. * @Description
  18. * @Author WL
  19. * @Date 2024/3/11
  20. **/
  21. public class SpireWordTest {
  22. public static void main(String[] args) {
  23. //创建document对象
  24. Document document = new Document("D:\\temp\\adocument2.docx");
  25. // bookmarkTest(document);
  26. // editPage(document);
  27. //修改表格
  28. // editTable(document);
  29. //添加行号
  30. // addLineNumber(document);
  31. //添加文本和设置样式
  32. // addTextAndSetStyle(document);
  33. //添加页脚
  34. // addFootRange(document);
  35. //删除页眉
  36. // clearRange(document);
  37. //替换页眉
  38. // replace(document);
  39. //添加页眉
  40. // addHeaderRange(document);
  41. //更改现有书签上的文字
  42. // replaceBookmarkContent(document);
  43. //添加图片
  44. // addPicture(document);
  45. document.saveToFile("D:\\temp\\adocument3.docx", FileFormat.Docx);
  46. //获取文本
  47. // String text = getText(document);
  48. // System.out.println(text);
  49. }
  50. private static void bookmarkTest(Document document) {
  51. //定位到书签
  52. BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
  53. //移除
  54. bookmarkNavigator.moveToBookmark("title");
  55. String title = "Spire.Doc for .NET 是一个专业的Word操作库,它可以帮助开发者在C#和VB.NET应用程序中创建、修改和转换Word文档。如果你想要修改书签处的内容样式,可以使用以下方法\n" +
  56. "Spire.Doc for .NET 是一个专业的Word操作库,它可以帮助开发者在C#和VB.NET应用程序中创建、修改和转换Word文档。如果你想要修改书签处的内容样式,可以使用以下方法";
  57. //使用文本替换原书签的内容, false表示不保留原来的格式
  58. bookmarkNavigator.replaceBookmarkContent(title, false);
  59. Bookmark bookmark = document.getBookmarks().get("title");
  60. Paragraph ownerParagraph = bookmark.getBookmarkStart().getOwnerParagraph();
  61. ParagraphFormat paragraphFormat = ownerParagraph.getStyle().getParagraphFormat();
  62. paragraphFormat.setFirstLineIndent(40f);
  63. ParagraphStyle styleContent = new ParagraphStyle(document);
  64. styleContent.setName("titleStyle");
  65. styleContent.getCharacterFormat().setFontName("宋体");
  66. styleContent.getCharacterFormat().setFontSize(20f);
  67. document.getStyles().add(styleContent);
  68. ownerParagraph.applyStyle("titleStyle");
  69. }
  70. /**
  71. * @Description 设置页边距或方向
  72. * @Param document
  73. * @Return void
  74. * @Author HZ_WL
  75. * @Date 2024/3/21
  76. **/
  77. private static void editPage(Document document) {
  78. Section section = document.getSections().get(0);
  79. //修改页边距
  80. /*MarginsF marginsF = new MarginsF();
  81. // marginsF.setAll(10);
  82. marginsF.setTop(50);
  83. marginsF.setBottom(10);
  84. marginsF.setLeft(10);
  85. marginsF.setRight(10);
  86. section.getPageSetup().setMargins(marginsF);*/
  87. //设置方向
  88. section.getPageSetup().setOrientation(PageOrientation.Landscape);
  89. }
  90. /**
  91. * @Description 修改表格
  92. * @Param document
  93. * @Return void
  94. * @Author HZ_WL
  95. * @Date 2024/3/21
  96. **/
  97. private static void editTable(Document document) {
  98. Section section = document.getSections().get(0);
  99. Table table = section.getTables().get(0);
  100. //替换数据
  101. TableCell tableCell = table.getRows().get(0).getCells().get(0);
  102. Paragraph paragraph = tableCell.getParagraphs().get(0);
  103. // paragraph.appendText("123");
  104. // paragraph.replace(Pattern.compile("序号"), "456");
  105. paragraph.replace("序号", "学号", true, true);
  106. TableCell tableCell1 = table.getRows().get(1).getCells().get(1);
  107. Paragraph paragraph1 = tableCell1.getParagraphs().get(0);
  108. paragraph1.replace("小明", "小民", true, true);
  109. //清空单元格数据
  110. TableCell tableCell2 = table.getRows().get(1).getCells().get(2);
  111. Paragraph paragraph2 = tableCell2.getParagraphs().get(0);
  112. paragraph2.getItems().clear();
  113. table.addRow(true);
  114. TableCell tableCell3 = table.getLastRow().getCells().get(0);
  115. table.getLastRow().getCells().remove(tableCell3);
  116. }
  117. /**
  118. * @Description 添加行号
  119. * @Param document
  120. * @Return void
  121. * @Author HZ_WL
  122. * @Date 2024/3/21
  123. **/
  124. private static void addLineNumber(Document document) {
  125. Section section = document.getLastSection();
  126. section.getPageSetup().setLineNumberingRestartMode(LineNumberingRestartMode.Restart_Page);
  127. section.getPageSetup().setLineNumberingStep(1);
  128. section.getPageSetup().setLineNumberingStartValue(1);
  129. // Paragraph paragraph = section.addParagraph();
  130. // paragraph.appendText("As an independent Word .NET component, Spire.Doc for .NET doesn't need Microsoft Word to be installed on the machine. " +
  131. // "However, it can incorporate Microsoft Word document creation capabilities into any developers .NET applications.");
  132. }
  133. /**
  134. * @Description 添加文本和设置样式
  135. * @Param document
  136. * @Return void
  137. * @Author HZ_WL
  138. * @Date 2024/3/21
  139. **/
  140. private static void addTextAndSetStyle(Document document) {
  141. Section section = document.getLastSection();
  142. Paragraph paragraph = section.addParagraph();
  143. TextRange textRange = paragraph.appendText("Hello world!");
  144. //倾斜
  145. // textRange.getCharacterFormat().setItalic(true);
  146. //转大写
  147. // textRange.getCharacterFormat().setAllCaps(true);
  148. //字体颜色
  149. // textRange.getCharacterFormat().setTextColor(Color.BLUE);
  150. //字符间距
  151. // textRange.getCharacterFormat().setCharacterSpacing(10);
  152. //字体大小
  153. // textRange.getCharacterFormat().setFontSize(20);
  154. //字体
  155. // textRange.getCharacterFormat().setFontName("Arial");
  156. //字体加粗
  157. // textRange.getCharacterFormat().setBold(true);
  158. //允许上下文替代
  159. // textRange.getCharacterFormat().setAllowContextualAlternates(true);
  160. }
  161. /**
  162. * @Description 添加页脚
  163. * @Param document
  164. * @Return void
  165. * @Author HZ_WL
  166. * @Date 2024/3/21
  167. **/
  168. private static void addFootRange(Document document) {
  169. Section section = document.addSection();
  170. HeaderFooter footer = section.getHeadersFooters().getFooter();
  171. Paragraph paragraph = footer.addParagraph();
  172. TextRange range = paragraph.appendText("这里是添加的页脚");
  173. range.getCharacterFormat().setFontSize(5);
  174. range.getCharacterFormat().setTextColor(Color.BLUE);
  175. }
  176. /**
  177. * @Description 清除页眉
  178. * @Param document
  179. * @Return void
  180. * @Author HZ_WL
  181. * @Date 2024/3/21
  182. **/
  183. private static void clearRange(Document document) {
  184. Paragraph paragraph = document.getSections().get(0).getHeadersFooters().getHeader().getParagraphs().get(0);
  185. paragraph.getChildObjects().clear();
  186. }
  187. /**
  188. * @Description 替换页眉
  189. * @Param document
  190. * @Return void
  191. * @Author HZ_WL
  192. * @Date 2024/3/21
  193. **/
  194. private static void replace(Document document) {
  195. Paragraph paragraph = document.getSections().get(0).getHeadersFooters().getHeader().getParagraphs().get(0);
  196. //case sensitive 是否区分大小写
  197. paragraph.replace("这里是添加的页眉", "这里是替换的页眉", false, false);
  198. }
  199. /**
  200. * @Description 添加页眉
  201. * @Param document
  202. * @Return void
  203. * @Author HZ_WL
  204. * @Date 2024/3/21
  205. **/
  206. private static void addHeaderRange(Document document) {
  207. Section section = document.addSection();
  208. HeaderFooter header = section.getHeadersFooters().getHeader();
  209. Paragraph paragraph = header.addParagraph();
  210. TextRange range = paragraph.appendText("这里是添加的页眉");
  211. range.getCharacterFormat().setFontSize(25);
  212. range.getCharacterFormat().setTextColor(Color.BLUE);
  213. }
  214. /**
  215. * @Description 更改现有书签上的文字
  216. * @Param document
  217. * @Return void
  218. * @Author HZ_WL
  219. * @Date 2024/3/21
  220. **/
  221. private static void replaceBookmarkContent(Document document) {
  222. BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document);
  223. bookmarksNavigator.moveToBookmark("title");
  224. bookmarksNavigator.replaceBookmarkContent("这是替换书签的标题", true);
  225. }
  226. /**
  227. * @Description 插入具有指定高度和宽度的图像
  228. * @Param document
  229. * @Return void
  230. * @Author HZ_WL
  231. * @Date 2024/3/21
  232. **/
  233. private static void addPicture(Document document) {
  234. //获取最后一个section
  235. Section newSec = document.getLastSection();
  236. // 创建 DocPicture 类的对象
  237. DocPicture picture1 = new DocPicture(document);
  238. // 从磁盘加载图片
  239. String images1 = "D:\\temp\\123.jpg";
  240. picture1.loadImage(images1);
  241. // 设置图片大小
  242. picture1.setWidth(180); //示例:80
  243. picture1.setHeight(180);//示例:50
  244. picture1.setHorizontalPosition(110); //示例:110.0F 水平位置
  245. picture1.setVerticalPosition(220); //示例:110.0F 垂直位置
  246. Paragraph picParagraph1 = newSec.addParagraph();
  247. picParagraph1.getChildObjects().add(picture1);
  248. }
  249. /**
  250. * @Description 从word文档中获取文本
  251. * @Param document
  252. * @Return 文本
  253. * @Author HZ_WL
  254. * @Date 2024/3/21
  255. **/
  256. public static String getText(Document document) {
  257. return document.getText();
  258. }
  259. }

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

闽ICP备14008679号