Export data check out the list collection to the word template

1. Background

  There is a demand to check out the loan recipients to achieve a single printing function in the project. The general idea is that the recipients achieve single export to word, and then convert it to pdf, uploaded to the ftp (see demand for this step can be replaced costs or elsewhere) to obtain an address, the address is returned to the front-end front-end to get this using a browser that comes with pdf print function, enables the printing.

2. Write export to word templates (for example in a single recipients)

 

Note: $ {receiveNo} may not be replaced in the replacement process, if this happens, is the template is the issue, the $ {receiveNo} entire copy to txt, then copy back to.

3.controller layer

 / ** 
 * Print Preview - Pilot into a docx, uploaded to ftp, ftp addresses obtained display 
 * / 
@RequestMapping (value = "/ PrintPreview / for appId {}", Method = {RequestMethod.POST, RequestMethod.GET} ) 
@ResponseBody 
public the WebResponse PrintPreview ( 
        the HttpServletRequest Request, 
        the HttpServletResponse Response, 
        @RequestParam (value = "for appId", = required to false ) for appId String, 
        @RequestParam (value = "receiveNo", = required to false ) String receiveNo 

) { 

    pager pager; 
    the Map <String, Object> = Map new new the HashMap <> ();
     the try {
        String path = request.getSession().getServletContext().getRealPath("/") + "rpt_template" + "/" + "word" + "/" + "receiveInfo.docx";
        String newPath = request.getSession().getServletContext().getRealPath("/") + "rpt_template" + "/" + "word" + "/" + "receiveInfoNW.docx";
        Integer page = 1;
        Integer rows = 99;
        pager = receiveService.getReceiveInfo(receiveNo, page, rows);
        FileUtils.copyFile(new File(newPath), new File(path));
        CustomXWPFDocument doc = receiveService.receiveInfoPdf(pager.getRows(), path);
        map = receiveService.handlePdf(request, doc);
    } catch (Exception e) {
        e.printStackTrace();
        return this.buildResponse("705", e.getMessage());
    }
    return buildResponse(map);

}

Note: To save the template duplicate, otherwise there will be the last export will accumulate, so use the new template replace.

4.service layer (service layer is mainly replace template information)

public  CustomXWPFDocument receiveInfoPdf(List<ReceiveInfoResult> info,String wordPath){
    Map<String, Object> data = new HashMap<>();
    data.put("${receiveNo}", info.get(0).getReceiveNo());
    data.put("${sectionName}", info.get(0).getSectionName());
    data.put("${receiveName}", info.get(0).getReceiveName());
    data.put("${receiveTime}", info.get(0).getReceiveTime());
    List<Map<String, Object>> receiveInfoList = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < info.size(); i++) {
        ReceiveInfoResult receiveInfo = info.get(i);
        Map<String, Object> content = new HashMap<>();
        content.put("序号", String.valueOf(i + 1));
        content.put("工器具类型", receiveInfo.getInstrumentTypeBig());
        content.put("工器具名称", receiveInfo.getInstrumentName());
        content.put("规格型号", receiveInfo.getInstrumentModel());
        content.put("RFID编码", receiveInfo.getRfid());
        content.put("位置", receiveInfo.getContainerNumber());
        content.put("归还时间", receiveInfo.getInTime());
        content.put("状态", receiveInfo.getInState());
        receiveInfoList.add(content);
    }
    data.put("${contentList}", receiveInfoList);
    CustomXWPFDocument doc = WorderToNewWordUtils.changWordReceiveInfo(wordPath, data);
    return doc;
}

The use wherein the main class util

  Generate word document template based on a single recipients

/ ** 
 * generated from single template word document recipients 
 * @param inputUrl template path 
 * @param textMap text needs to be replaced 
 * @return 
 * / 
public  static CustomXWPFDocument changWordReceiveInfo (String inputUrl, the Map <String, Object> textMap) { 
    CustomXWPFDocument Document = null ;
     the try {
         // Get docx analysis target 
        Document = new new CustomXWPFDocument (POIXMLDocument.openPackage (inputUrl)); 

        // parse text paragraph objects Alternatively 
        the try { 
            WorderToNewWordUtils.changeText (Document, textMap); 
        }the catch (Exception E) { 
            e.printStackTrace (); 
        } 
        // parse table object replacement 
        WorderToNewWordUtils.changeTableReceive (Document, textMap); 
    } the catch (IOException E) { 
        e.printStackTrace (); 
    } 
    return Document; 
}

 Replace the table object method

/ ** 
 * alternative method of the spreadsheet object 
 * @param Document docx analysis target 
 * @param information textMap requires replacement set
  * / 
public  static  void changeTableReceive (CustomXWPFDocument Document, the Map <String, Object> textMap) {
     // Get the table object set 
    List <XWPFTable> = tables document.getTables ();
     // dynamically add list line 
    XWPFTable tables.get table1 = (0); // get the first table
      // XWPFTableRow table1 = tables.get (0) .getRow (0 ); 
    List <the Map <String, Object ContentList >> = (List <the Map <String, Object >>) textMap.get ( "ContentList $ {}" );
     IF (ContentList!= null && contentList.size ()> 0 ) {
         for ( int I = 0; I <contentList.size (); I ++ ) { 
            XWPFTableRow Row = table1.insertNewTableRow (. 1 + I); // for the first row to the 2 + i next add a new row
             // XWPFTableRow table1 = row; 
            . row.createCell () the setText ((String) contentList.get (I) .get ( "No.")); // add a second column 
            row.createCell () .setText ((String) contentList.get (i ) .get ( " industrial equipment type")); // add a third column 
            row.createCell () setText ((String) contentList.get (i) .get (. "industrial equipment name")); // add a fourth column 
            row.createCell () setText ((String) contentList.get (i) .get ( ".Specifications Model "));// add a fifth columns 
            row.createCell () setText ((String) contentList.get (i) .get ( "RFID code"));. // add a fifth columns 
            row.createCell () setText ((. String) contentList.get (i) .get ( " position")); // add a fifth column 
            row.createCell () setText ((String) contentList.get (i) .get ( " return time")). ; // add a fifth columns 
            row.createCell () setText ((String) contentList.get (i) .get ( " state"));. // add a fifth columns 
        } 
    } 

}

 Convert pdf, upload to ftp

/**
 *
 * @param request
 * @param doc
 * @return 获取PDF路径
 * @throws Exception
 */
public   Map<String,Object> handlePdf(HttpServletRequest request, CustomXWPFDocument doc) throws Exception {
    //生成地址   创建PDF路径   生成wordPath 开始
    String newWordPath = request.getSession().getServletContext().getRealPath("/") +
            "rpt_template/temp_file/" + UUID.randomUUID().toString() + ".docx";
    File newFile = new File(newWordPath);
    newFile.createNewFile();//Add a file 
    FileOutputStream fopts = new new FileOutputStream (newFile); 
    doc.write (fopts); 
    fopts.close (); 
    doc.close (); 
    // generate end wordPath
     // Create a return to the Map 
    the Map <String, Object> = resultMap new new the HashMap <> ();
     // create a PDF path 
    String pdfTeamPath = request.getSession () getServletContext ( ) getRealPath ( "/") + "rpt_template" + "/" + "temp_file" + "/" + UUID... randomUUID () + "of.pdf" ;
     // Word format conversion to pdf (fileUrl file path / pdfTeamPath path to PDF) 
    FileUtil.doc2pdf (newWordPath, pdfTeamPath);
    // upload ftp server 
    File pdfFile = new new File(pdfTeamPath);
    String pdfPath = FTPUtil.uploadFile("files/pdf/", pdfFile, pdfFile.getName());
    String pdfUrl = ConstantsUtil.photoPath + pdfPath;
    //获取路径
    resultMap.put("fileUrl", pdfUrl);
    //删除文件 pdfTeamPath
    ExportSafetyNoticeRest.deleteFile(pdfTeamPath);
    ExportSafetyNoticeRest.deleteFile(newWordPath);
    resultMap.put("worfUrl", newWordPath);
    return resultMap;
}

 end!

Guess you like

Origin www.cnblogs.com/fyy151617/p/12123439.html
Recommended