微信小程序下载word

  后台返回数据流给请求方,Uni-app中使用uni.downloadFile。

前端代码

exportFile(){
    uni.showLoading({
        mask:true
    })
    uni.downloadFile({
        url: root+'/portal/offer/record/exportBaojiaWord?list_id='+this.item.list_id, 
        success: (res) => {
            if (res.statusCode === 200) {
                uni.openDocument({
                    filePath:res.tempFilePath,
                    fileType:"docx",
                    showMenu:true
                })
                // console.log('下载成功');
            }
        },
        complete:(res)=>{
            // console.log(res)
            uni.hideLoading()
        }
    });
},

后端代码

@RequestMapping("/record/exportBaojiaWord")
public void exportBaojiaWord(HttpServletRequest request,HttpServletResponse response) {
    try {
        PageData pd = this.getPageData();
        offerService.exportBaojiaWord(pd,response);
    } catch (Exception e) {
        logger.error("OfferRecordController: getRecordPackageListByPage error; ", e);
    }
}



/**
     * 导出报价记录world
     * @param pageData
     * @return
     */
public void exportBaojiaWord(PageData pageData, HttpServletResponse response) {
    /**
         * 
         * 4. 获取word模板
         * 5. 写入数据到word模板
         * 6. 流下载
         */
    Map<String,String> modelMap = new HashMap<>();
    List<List<List<String>>> list = new ArrayList<>();

    String inputUrl = "model.docx";


    Random random = new Random();
    String outputFileName = "报价记录"+random.nextInt(20)+".docx";


    try{
        String path = this.getClass().getClassLoader().getResource("files/"+inputUrl).getPath();
        String filePath = URLDecoder.decode(path, "UTF-8");
        log.info(filePath);
        inputUrl = filePath;

        response.setContentType("application/msword;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        WordToNewWordUtils.changWord(inputUrl, outputStream, modelMap, list);
    }catch (IOException e){
        log.error("",e);
    }
}



public static boolean changWord(String inputUrl, OutputStream fileOutputStream,
                                    Map<String, String> textMap, List<List<List<String>>> tableList) {

    //模板转换默认成功
    boolean changeFlag = true;
    nowTableIndex = -1;
    try {
        //获取docx解析对象
        XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
        //解析替换文本段落对象
        WordToNewWordUtils.changeText(document, textMap);
        //解析替换表格对象
        WordToNewWordUtils.changeTable(document, textMap, tableList);

        //生成新的word
        document.write(fileOutputStream);
    } catch (IOException e) {
        log.error("生成word文档:",e);
        changeFlag = false;
    }

    return changeFlag;

}

 

注意

response.setContentType("application/msword;charset=utf-8");

如果是传excel,pdf等,要变更这里的contentType,否则微信小程序下载下来就是未知文件。

Mime-Types(mime类型) Dateiendung(扩展名) Bedeutung
application/msexcel *.xls *.xla Microsoft Excel Dateien
application/mshelp *.hlp *.chm Microsoft Windows Hilfe Dateien
application/mspowerpoint *.ppt *.ppz *.pps *.pot Microsoft Powerpoint Dateien
application/msword *.doc *.dot Microsoft Word Dateien

application/octet-stream

*.exe exe
application/pdf *.pdf Adobe PDF-Dateien
application/post****** *.ai *.eps *.ps Adobe Post******-Dateien
application/rtf *.rtf Microsoft RTF-Dateien
application/x-httpd-php *.php *.phtml PHP-Dateien
     
application/x-java****** *.js serverseitige Java******-Dateien
application/x-shockwave-flash *.swf *.cab Flash Shockwave-Dateien
application/zip *.zip ZIP-Archivdateien
audio/basic *.au *.snd Sound-Dateien
audio/mpeg *.mp3 MPEG-Dateien
audio/x-midi *.mid *.midi MIDI-Dateien
audio/x-mpeg *.mp2 MPEG-Dateien
audio/x-wav *.wav Wav-Dateien
image/gif *.gif GIF-Dateien
image/jpeg *.jpeg *.jpg *.jpe JPEG-Dateien
image/x-windowdump *.xwd X-Windows Dump
text/css *.css CSS Stylesheet-Dateien
text/html *.htm *.html *.shtml -Dateien
text/java****** *.js Java******-Dateien
text/plain *.txt reine Textdateien
video/mpeg *.mpeg *.mpg *.mpe MPEG-Dateien
video/vnd.rn-realvideo *.rmvb realplay-Dateien
video/quicktime *.qt *.mov Quicktime-Dateien
video/vnd.vivo *viv *.vivo Vivo-Dateien

 

posted @ 2023-05-22 11:15  伟衙内  阅读(295)  评论(0编辑  收藏  举报