需要引用了对应的jar包
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>5.2.0</version> </dependency> </dependencies> <repositories> <repository> <id>com.e-iceblue</id> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories>
public class TestCellss { public static void main(String[] args) { String fileUrl = "/Users/mac/soft/123/" setFooter(fileUrl) } }
//获取文件夹下所有的文件 public static List<String> getFileName(String fileUrl) { List<String> list = new ArrayList<String>(); // String folderPath = "/Users/mac/soft/XXX"; // 替换为你的文件夹路径 File folder = new File(fileUrl); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile() && file.getName().endsWith(".docx")) { // 假设只加载.docx文件 list.add(file.getName()); } } return list; }
页脚签的横线需要借助XWPFTable表格去设置
/** * 设置页脚 */ public static void setFooter(String fileUrl) { List<String> listFile = getFileName(fileUrl); //创建Document的对象 Document document = new Document(); //载入Word文档 for (int i = 0; i < listFile.size(); i++) { document.loadFromFile(fileUrl + listFile.get(i)); //获取文档第一节 Section section = document.getSections().get(0); //获取第一节的页脚 HeaderFooter footer1 = section.getHeadersFooters().getFooter(); Table table= section.addTable(true); //添加Page和NumPages域到页脚中并设置页码格式 Paragraph footerParagraph = footer1.addParagraph(); footerParagraph.appendText("Version 1.0 "); footerParagraph.appendText(" Page "); //设置页脚对齐方式用最笨方法直接加空格 footerParagraph.appendField("页码", FieldType.Field_Page); //设置页脚字体和大小 footerParagraph.getStyle().getCharacterFormat().setFontName("Times New Roman"); footerParagraph.getStyle().getCharacterFormat().setFontSize(8); footerParagraph.getStyle().getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left); //保存文档 document.saveToFile(fileUrl + listFile.get(i)); } }