利用word模板进行操作。
try {
request.setCharacterEncoding("UTF-8");
String templateDocx =request.getSession().getServletContext().getRealPath("\\") + "res\\MyTemplate2.docx";
FileInputStream in = new FileInputStream(templateDocx);
//用自定义解析类获得document
XWPFDocument document = new XWPFDocument(in);
// replace special string in file
Map<String,String> map = new HashMap<String,String>();
map.put("${tableName}", fileName);
Iterator<XWPFParagraph> itPara = document
.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
String oneparaString = runs.get(i).getText(
runs.get(i).getTextPosition());
for (Map.Entry<String, String> entry : map
.entrySet()) {
oneparaString = oneparaString.replace(
entry.getKey().toString(), entry.getValue().toString());
}
runs.get(i).setText(oneparaString, 0);
}
}
//add table content
XWPFTable table ;
XWPFTableRow row ;
XWPFTableCell cell ;
// JBXX
table = document.getTables().get(0);
table.removeRow(0);
row = table.createRow();
cell = row.createCell();
cell.setText("表格属性");
cell = row.createCell();
cell.setText("值");
for (int i = 0; i < dataCol1.length; i++) {
row = table.createRow();
cell = row.getCell(0);
if(null != dataHeader1[i] && dataHeader1[i].toString().length() > 0)
cell.setText(dataHeader1[i].toString());
cell = row.getCell(1);
if(null != JBXX.get(dataCol1[i]) && JBXX.get(dataCol1[i]).toString().length() > 0)
cell.setText(JBXX.get(dataCol1[i]).toString());
}
//ZDXX
table = document.getTables().get(1);
table.removeRow(0);
row = table.createRow();
for (int i = 0; i < dataCol2.length; i++) {
cell = row.createCell();
if (null != dataHeader2[i] && dataHeader2[i].toString().length() > 0) {
cell.setText(dataHeader2[i].toString());
}
}
Map<String, Object> map2;
for (int i = 0; i < ZDXX.size() ; i++) {
row = table.createRow();
map2 = ZDXX.get(i);
for (int j = 0; j < dataCol2.length; j++) {
cell = row.getCell(j);
if (null != map2.get(dataCol2[j]) && map2.get(dataCol2[j]).toString().length() > 0) {
cell.setText(map2.get(dataCol2[j]).toString() );
}
}
}
//文件输出流
OutputStream fos = response.getOutputStream();
//文件输出相关信息
String outputFileName = fileName+"_"+ DateUtil.getDate() + ".docx";
response.setContentType("application/octet-stream");
// response.setHeader("Content-disposition", "attachment; filename=\""
// + URLEncoder.encode(outputFileName, "UTF-8") + "\"");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(outputFileName.getBytes("GBK"), "ISO8859_1"));
document.write(fos);
fos.flush();
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}