html导出成word

maven坐标


            fr.opensagres.xdocreport
            org.apache.poi.xwpf.converter.core
            1.0.6
        
        
            fr.opensagres.xdocreport
            org.apache.poi.xwpf.converter.xhtml
            1.0.6
        
        
            org.apache.poi
            poi-scratchpad
            3.14
        
        
            org.apache.poi
            poi
            3.14
        
        
            org.apache.poi
            poi-ooxml
            3.14
        
        
            org.apache.xmlbeans
            xmlbeans
            2.6.0
        

工具类代码

public Map writeWordFile(String txt,String fileName,HttpServletRequest request) {
        String uri = "";
        String realPath = null;
        fileName=fileName+System.currentTimeMillis()+"";
        HashMap map = new HashMap<>();

        String outFileName=fileName+".doc";
        try {
            if (!"".equals(uploadPath)) {
                // 检查目录是否存在
                File fileDir = new File(uploadPath);

                if (!fileDir.exists()){
                    fileDir.mkdir();
                }

                byte b[] = txt.getBytes();
                ByteArrayInputStream bais = new ByteArrayInputStream(b);
                POIFSFileSystem poifs = new POIFSFileSystem();
                DirectoryEntry directory = poifs.getRoot();
                DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
                FileOutputStream ostream = new FileOutputStream(uploadPath+ outFileName);
                poifs.writeFilesystem(ostream);

                /*关闭流*/
                ostream.close();
                bais.close();

                //创建访问路径
                realPath = request.getSession().getServletContext().getRealPath(fileName);
                System.out.println(realPath);
                uri = request.getScheme() + "://" + request.getServerName() + ":" +
                        request.getServerPort() + accessPath.substring(0,accessPath.lastIndexOf("/")+1)+outFileName;

                map.put("uri",uri);
                map.put("fileName",outFileName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

controller方法调用

/**
*fileName 文件名字
*txt  html内容
*/
    @RequestMapping("/translate")
    @ResponseBody
    public Object translate(String fileName,String txt,HttpServletRequest request) {
      
                Map map = writeWordFile(txt, fileName, request);
                
     
    }

你可能感兴趣的:(java)