springMVC method for exporting word templates

  • 2020-08-22 22:06:20
  • OfStack

This article shares the specific code of springMVC export word template for your reference. The specific content is as follows

controller call


@RequestMapping(value = "/exportWord")
public void exportWord(HttpServletResponse response, HttpServletRequest request) throws IOException {
  String templatePath = request.getServletContext().getRealPath("") + "/template/ Tax source information comparison .docx"; 
  String fileName = new String(" Tax source information comparison ".getBytes("gb2312"), "ISO8859-1") + ".docx";
  /* data */
  Map<String, Object> params = new HashMap<String, Object>(); 
  params.put("${name}", "aaaa"); 
  params.put("${sex}", "bbbb");

  TempleWordUtil wordUtil = new TempleWordUtil();

  XWPFDocument doc; 
  InputStream is = new FileInputStream(templatePath);
 // is = getClass().getClassLoader().getResourceAsStream(templatePath); 
  doc = new XWPFDocument(is);  // Can only use .docx the 

  wordUtil.replaceInPara(doc, params); 
  // Replace the variables in the table  
  wordUtil.replaceInTable(doc, params); 
  OutputStream os = response.getOutputStream(); 

  response.setContentType("application/vnd.ms-excel"); 
  response.setHeader("Content-disposition", "attachment;filename=" + fileName); 

  doc.write(os); 

  wordUtil.close(os); 
  wordUtil.close(is); 

  os.flush(); 
  os.close(); 

}

TempleWordUtil tools


import org.apache.poi.xwpf.usermodel.*; 
  
import java.io.*; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 
/**
 *  write word Utility class 
 * @author z
 *
 */
public class TempleWordUtil {
 
  /** 
   *  Replace the variables in the paragraph  
   * 
   * @param doc   The document to be replaced  
   * @param params  Parameter, imported data  
   */ 
  public void replaceInPara(XWPFDocument doc, Map<String, Object> params) { 
    Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator(); 
    XWPFParagraph para; 
    while (iterator.hasNext()) { 
      para = iterator.next(); 
      this.replaceInPara(para, params); 
    } 
  } 
  
  /** 
   *  Replace the variables in the paragraph  
   * 
   * @param para   The paragraph to be replaced  
   * @param params  parameter  
   */ 
  public void replaceInPara(XWPFParagraph para, Map<String, Object> params) { 
    List<XWPFRun> runs; 
    //Matcher matcher; 
    if (this.matcher(para.getParagraphText()).find()) { 
      runs = para.getRuns(); 
  
      int start = -1; 
      int end = -1; 
      String str = ""; 
      for (int i = 0; i < runs.size(); i++) { 
        XWPFRun run = runs.get(i); 
        String runText = run.toString(); 
        if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) { 
          start = i; 
        } 
        if ((start != -1)) { 
          str += runText; 
        } 
        if ('}' == runText.charAt(runText.length() - 1)) { 
          if (start != -1) { 
            end = i; 
            break; 
          } 
        } 
      } 
  
      for (int i = start; i <= end; i++) { 
        para.removeRun(i); 
        i--; 
        end--; 
      } 
  
      for (String key : params.keySet()) { 
        if (str.equals(key)) { 
          para.createRun().setText((String) params.get(key)); 
          break; 
        } 
      } 
  
  
    } 
  } 
  
  /** 
   *  Replace the variables in the table  
   * 
   * @param doc   The document to be replaced  
   * @param params  parameter  
   */ 
  public void replaceInTable(XWPFDocument doc, Map<String, Object> params) { 
    Iterator<XWPFTable> iterator = doc.getTablesIterator(); 
    XWPFTable table; 
    List<XWPFTableRow> rows; 
    List<XWPFTableCell> cells; 
    List<XWPFParagraph> paras; 
    while (iterator.hasNext()) { 
      table = iterator.next(); 
      rows = table.getRows(); 
      for (XWPFTableRow row : rows) { 
        cells = row.getTableCells(); 
        for (XWPFTableCell cell : cells) { 
          paras = cell.getParagraphs(); 
          for (XWPFParagraph para : paras) { 
            this.replaceInPara(para, params); 
          } 
        } 
      } 
    } 
  } 
  
  /** 
   *  Regular matching string  
   * 
   * @param str 
   * @return 
   */ 
  private Matcher matcher(String str) { 
    Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE); 
    Matcher matcher = pattern.matcher(str); 
    return matcher; 
  } 
  
  /** 
   *  Close the input stream  
   * 
   * @param is 
   */ 
  public void close(InputStream is) { 
    if (is != null) { 
      try { 
        is.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
  
  /** 
   *  Close the output stream  
   * 
   * @param os 
   */ 
  public void close(OutputStream os) { 
    if (os != null) { 
      try { 
        os.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
  
}

Related articles: