<span style="font-size:14px;">public String print_cbht(String filename, Map<String, String> map,
List<Dk> list_dk_cbd) {
// TODO Auto-generated method stub
String path = "";
String xh = KeyGeneratorHelper.generateNumber();
String path1 = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
path = path1.substring(1, path1.indexOf("/WEB-INF/"))+"/PrintMuban/"+filename+".doc";
String destFile=path1.substring(1, path1.indexOf("/WEB-INF/"))+"/temp/"+filename+xh+".doc";
HWPFDocument document=replaceDoc_cbht(path, map,list_dk_cbd);
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
try {
document.write(ostream);
OutputStream outs=new FileOutputStream(destFile);
outs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Base64.encodeBase64String(ostream.toByteArray());
}
private HWPFDocument replaceDoc_cbht(String path, Map<String, String> map,
List<Dk> list_dk_cbd) {
// TODO Auto-generated method stub
File file = new File(path);
try {
// 读取word模板
FileInputStream fis = new FileInputStream(file);
POIFSFileSystem pfs = new POIFSFileSystem(fis);
HWPFDocument doc = new HWPFDocument(pfs);
// 读取word文本内容
Range bodyRange = doc.getRange();
for (Map.Entry<String, String> entry : map.entrySet()) {
if(null == entry.getValue()) {
bodyRange.replaceText("${" + entry.getKey() + "}", " ");
} else {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
}
TableIterator it = new TableIterator(bodyRange);
// 迭代文档中的表格
while (it.hasNext()) {
Table tb = (Table) it.next();
// 迭代行,默认从0开始
for (int i = 0; i < tb.numRows(); i++) {
if(i>1 && i<=list_dk_cbd.size()+1) {
TableRow tr = tb.getRow(i);
// 迭代列,默认从0开始
for (int j = 0; j < tr.numCells(); j++) {
TableCell td = tr.getCell(j);// 取得单元格
// 取得单元格的内容
if(j == 1) {
td.insertBefore( null ==list_dk_cbd.get(i-2).getDkmc()?"":list_dk_cbd.get(i-2).getDkmc());
}
if(j == 2) {
td.insertBefore(null ==list_dk_cbd.get(i-2).getQqmj()?"":list_dk_cbd.get(i-2).getQqmj()+"");
}
if(j == 3) {
td.insertBefore(null ==list_dk_cbd.get(i-2).getDkdz()?"":list_dk_cbd.get(i-2).getDkdz());
}
if(j == 4) {
td.insertBefore(null ==list_dk_cbd.get(i-2).getDknz()?"":list_dk_cbd.get(i-2).getDknz());
}
if(j == 5) {
td.insertBefore(null ==list_dk_cbd.get(i-2).getDkxz()?"":list_dk_cbd.get(i-2).getDkxz());
}
if(j == 6) {
td.insertBefore(null ==list_dk_cbd.get(i-2).getDkdz()?"":list_dk_cbd.get(i-2).getDkdz());
}
}
}
}
}
return doc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}</span>
其中表格都是以0开始的java中word模板导出
最新推荐文章于 2023-08-16 14:05:40 发布