admin管理员组

文章数量:1794759

Poi 生成word设置页边距

Poi 生成word设置页边距

  • 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>
  • 相关代码
  • import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar; import org.openxmlformats.schemas.wordprocessingml.x2006.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

    我的其他文章

    亲身分享 一次 字节跳动 真实面试经历和面试题

    其他薅羊毛网站

    自己做的小商城,感兴趣可以相互讨论技术呀!

    字节小柜:store.ityao/

    本文标签: poiword页边距