转为word的代码如下:
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class WordUtils {
public static void main(String[] args) throws Exception {
String imgPath = "C:\\Users\\Administrator\\Desktop\\timg.jpg";
BASE64Encoder encoder = new BASE64Encoder();
String imgStr = encoder.encode(encode(imgPath));
System.out.println(imgStr);
// 这里只是一个示例,key=value的格式,这里的key对应的ftl文件占位符{}中的字符串。
Map<String, Object> dataMap = new HashMap<String, Object>() {{
put("imgStr",imgStr);
put("province","北京市");
put("city","海淀区");
put("school","");
put("class","二三班");
}};
//处理excel,将其中的数据填充至模板中,最后生成word。
List<ERReport> datas = ExcelUtils.readExcel(new FileInputStream(new File(filePath)), ERReport.class);
datas.forEach((ERReport e) -> {
try {
processTemplate(e, “Your File Name”);
System.out.println("转换成功");
} catch (Exception ex) {
LOGGER.error("Excel转换Word错误.", ex);
}
});
}
private static byte[] encode(String imagePath) throws IOException {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imagePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
return data;
}
}
public static void processTemplate(Object dataMap, String fileName) throws IOException, TemplateException {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(WordUtils.class, "/templates");
Template template = configuration.getTemplate("template.ftl");
File file = new File("C:\\Users\\Administrator\\Desktop\\" + fileName + ".docx");
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
template.process(dataMap, bufferedWriter);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.