java excel模板转html

本文介绍了一种将Excel模板转换为HTML的方法,并详细解释了如何使用Java实现这一过程。通过读取Excel文件并替换其中的特定占位符,可以生成带有自定义样式的HTML页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


模板

先查出需要替换的内容,然后放入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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值