700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JAVA - 使用Apache POI生成word(三)设置页边距

JAVA - 使用Apache POI生成word(三)设置页边距

时间:2021-04-27 15:50:07

相关推荐

JAVA - 使用Apache POI生成word(三)设置页边距

JAVA - 使用Apache POI生成word(三)设置页边距

1. pom引入依赖

<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version></dependency>

2. 相关代码

import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.openxmlformats.schemas.wordprocessingml.x.main.CTPageMar;import org.openxmlformats.schemas.wordprocessingml.x.main.CTSectPr;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.math.BigInteger;

/*** 设置页边距** @param document doc对象* @param left左边距* @param right 右边距* @param top上边距* @param bottom 下边距*/public static void setPageMargin(XWPFDocument document,long left,long right,long top,long bottom) {CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();CTPageMar pageMar = sectPr.addNewPgMar();pageMar.setLeft(BigInteger.valueOf(left));pageMar.setRight(BigInteger.valueOf(right));pageMar.setTop(BigInteger.valueOf(top));pageMar.setBottom(BigInteger.valueOf(bottom));}/*** 保存文件** @param document doc对象* @param savePath 保存路径* @param fileName 文件名称*/public static void saveDoc(XWPFDocument document, String savePath, String fileName) throws IOException {File file = new File(savePath);if (!file.exists()) {// 判断生成目录是否存在,不存在时创建目录。file.mkdirs();}// 保存fileName += ".docx";FileOutputStream out = new FileOutputStream(new File(savePath + File.separator + fileName));document.write(out);// 关闭资源out.flush();out.close();document.close();}public static void main(String[] args) throws IOException {XWPFDocument document = new XWPFDocument();// 将页边距设置为1厘米setPageMargin(document, 567, 567, 567, 567);// 保存文件String savePath = "D:\\poi";String fileName = "PoiWord";saveDoc(document, savePath, fileName);}

结果如下:

取值规则

规则是磅数 * 20

例设置上、下、左、右的页边距为1CM,1 * 28.5 * 20 = 567

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。