Java poi导出带html标签内容的word文档

该代码段展示了一个使用Java将富文本内容转换并导出为Word文档(.docx)的示例。通过设置特定的XML头部来定义文档视图,并利用POIFSFileSystem和DocumentEntry创建WordDocument,然后通过HttpServletResponse以特定的MIME类型和Content-Disposition头将文件发送到客户端下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void exportWord(HttpServletResponse response, String content, String fileName) throws Exception {
        try {
            // 设置导出的word为页面视图
            // 不设置直接使用content word打开为web视图
            String str = " <!--[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]-->";
            // 其中content为富文本编辑器生成的内容
            String h = " <html 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'  ";
            content =h+"<head>"+"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"+str+"</head><body>"+content+"</body> </html>";

            // 设置编码
            byte bytes[] = content.getBytes("utf-8");
            //将字节数组包装到流中
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

            // 设置word格式
            POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
            DirectoryEntry directory = poifsFileSystem.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", byteArrayInputStream);

            // 输出文件
            // 导出word格式
            // docx -- application/vnd.openxmlformats-officedocument.wordprocessingml.document
            // doc -- application/msword
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String( (fileName + ".docx").getBytes(),
                            "iso-8859-1"));

            OutputStream outputStream = response.getOutputStream();
            poifsFileSystem.writeFilesystem(outputStream);
            byteArrayInputStream.close();
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

文件格式

Ext

MIME Type

 .doc

application/msword

.dot

application/msword

.docx

application/vnd.openxmlformats-officedocument.wordprocessingml.document

.dotx

application/vnd.openxmlformats-officedocument.wordprocessingml.template

.docm

application/vnd.ms-word.document.macroEnabled.12

.dotm

application/vnd.ms-word.template.macroEnabled.12

.xls

application/vnd.ms-excel

.xlt

application/vnd.ms-excel

.xla

application/vnd.ms-excel

.xlsx

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

.xltx

application/vnd.openxmlformats-officedocument.spreadsheetml.template

.xlsm

application/vnd.ms-excel.sheet.macroEnabled.12

.xltm

application/vnd.ms-excel.template.macroEnabled.12

.xlam

application/vnd.ms-excel.addin.macroEnabled.12

.xlsb

application/vnd.ms-excel.sheet.binary.macroEnabled.12

.ppt

application/vnd.ms-powerpoint

.pot

application/vnd.ms-powerpoint

.pps

application/vnd.ms-powerpoint

.ppa

application/vnd.ms-powerpoint

.pptx

application/vnd.openxmlformats-officedocument.presentationml.presentation

.potx

application/vnd.openxmlformats-officedocument.presentationml.template

.ppsx

application/vnd.openxmlformats-officedocument.presentationml.slideshow

.ppam

application/vnd.ms-powerpoint.addin.macroEnabled.12

.pptm

application/vnd.ms-powerpoint.presentation.macroEnabled.12

.potm

application/vnd.ms-powerpoint.template.macroEnabled.12

.ppsm

application/vnd.ms-powerpoint.slideshow.macroEnabled.12

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值