模板
先查出需要替换的内容,然后放入map中 键值对应 ,调用prepareHtmlForExcel方法传入excel路径,map对象,当前修改的对象id(为了生成唯一html和css文件)
public String toCopyFormHtml(Integer copy_id,Integer type){
Map<String, String> map = new HashMap<String, String>();JSONObject result = new JSONObject();
try {
String templatePath = SysConfigManager.getInstance().getProperty("/config/system/template");
CopyForm copyForm = copyFormService.getCopyFormAndBasepropertyById(copy_id);
map.put("#{name}", copyForm.getBaseProperty().getName());
map.put("#{total_num}", copyForm.getTotal_num().toString());
map.put("#{note}", copyForm.getNote());
String html = PrintUtils.prepareHtmlForExcel(templatePath + "/"+ type +"/copyform.xlsx", type, map,copy_id);
result.put("html","/temp/"+ type +"/"+ html + ".html");
result.put("flag", true);
} catch (Exception e) {
result.put("flag", false);
e.printStackTrace();
}
return JSON.toJSONString(result);
}
public static String prepareHtmlForExcel(String excelPath,Integer type,Map<String, String> paraMap,Integer object_id) throws Exception{
String extension = FilenameUtils.getExtension(excelPath);
Workbook wk = null;
Assert.notNull(extension, "file extension not found");
if(extension.toLowerCase().equals("xlsx")){
wk = new XSSFWorkbook(new FileInputStream(excelPath));
}else if(extension.toLowerCase().equals("xls")){
wk = new HSSFWorkbook(new FileInputStream(excelPath));
}else{
throw new RuntimeException("extension not support");
}
String tempFileName = type +"_"+ object_id;
String html = ExcelToHtmlUtil.toAllHtml(wk,tempFileName);
String replaceValue = null;
for (Map.Entry<String, String> entry : paraMap.entrySet()) {
replaceValue = entry.getValue();
if(StringUtils.isBlank(replaceValue)){
replaceValue = "";
}
html = html.replace(entry.getKey(),replaceValue);
}
String rootPath = SysConfigManager.getInstance().getProperty("/config/system/temp");
File htmlFile = new File(rootPath + "/" + type + "/" + tempFileName + ".html");
File htmlFileParent = htmlFile.getParentFile();
if(!htmlFileParent.exists()){
htmlFileParent.mkdirs();
}
File styleFile = new File(rootPath + "/" + type + "/" + tempFileName + ".css");
File styleFileParent = htmlFile.getParentFile();
if(!styleFileParent.exists()){
styleFileParent.mkdirs();
}
Document document = Jsoup.parse(html);
Element element = document.getElementsByTag("style").get(0);
String styleContent = element.html();
FileUtils.writeStringToFile(htmlFile, html, "UTF-8");
FileUtils.writeStringToFile(styleFile, styleContent, "UTF-8");
return tempFileName;
}