1. 程式人生 > >jsoup填充內容然後html轉word

jsoup填充內容然後html轉word

模板

<!DOCTYPE html>
<html lang="en" xmlns:v='urn:schemas-microsoft-com:vml'xmlns:o='urn:schemas-microsoft-com:office:office'xmlns:w='urn:schemas-microsoft-com:office:word'xmlns:m='http://schemas.microsoft.com/office/2004/12/omml'xmlns='http://www.w3.org/TR/REC-html40'  xmlns='http://www.w3.org/1999/xhtml'>
<head> <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</
w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><
w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]--> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> </html>
<dependency>
   <groupId>org.jsoup</groupId>
   <artifactId>jsoup</artifactId>
   <version>1.10.3</version>
</dependency>
/*
    *   content 資料
    *   path 儲存路徑
    *   fileModPath 模板檔案路徑
  * */
public static boolean htmlToWord(String content,String fileName,String path,String fileModPath){
        try {
            //將資料寫入模板html的body中
//            InputStream html=UeditorToDoc.class.getResourceAsStream(fileModPath);
InputStream html=UeditorToDoc.class.getClassLoader().getResourceAsStream(fileModPath);//需要一個html模板
String conte=getContent(html);
Document document= Jsoup.parse(conte);
Element body=document.body();
body.html(content);
/* 生成doc */
File file=new File(path+fileName+".html");
FileWriter fileWriter=new FileWriter(file);
String htmls=new String(document.html().getBytes("UTF-8"),"UTF-8");
fileWriter.write(htmls);
fileWriter.close();
html.close();
File file1=new File(path+fileName+".doc");
            if(file.renameTo(file1)){
                return true;
}else {
                return false;
}

        } catch (Exception e) {

            e.printStackTrace();
            return false;
}
    }