注:我使用的word 2016
功能简介:
(1)使用jsoup解析html得到我用来生成word的文本(这个你们可以忽略)
(2)生成word、设置页边距、设置页脚(页码),设置页码(文本)
一、解析html
Document doc = Jsoup.parseBodyFragment(contents); Element body = doc.body(); Elements es = body.getAllElements();
二、循环Elements获取我需要的html标签
boolean tag = false; for (Element e : es) { //跳过第一个(默认会把整个对象当做第一个) if(!tag) { tag = true; continue; } //创建段落:生成word(核心) createXWPFParagraph(docxDocument,e); }
三、生成段落
/** * 构建段落 * @param docxDocument * @param e */ public static void createXWPFParagraph(XWPFDocument docxDocument, Element e){ XWPFParagraph paragraph = docxDocument.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(e.text()); run.setTextPosition(35);//设置行间距 if(e.tagName().equals("titlename")){ paragraph.setAlignment(ParagraphAlignment.CENTER);//对齐方式 run.setBold(true);//加粗 run.setColor("000000");//设置颜色--十六进制 run.setFontFamily("宋体");//字体 run.setFontSize(24);//字体大小 }else if(e.tagName().equals("h1")){ addCustomHeadingStyle(docxDocument, "标题 1"