業務場景: 根據給定的模板word/excel進行數據填充和輸出. 另外對於一些業務, 需要把輸出的文件進行文件上傳的話.則要先把文件輸出到一個臨時文件中, 然後再調用系統的文件上傳功能.
word
word文檔需要使用其.xml文檔格式.在IDE中方便格式化和編碼.主要是寫佔位符,如 ${student.name!""}. ps: 對於word中所有佔位符均不能輸出null,否則會報錯.下面直接上代碼
//填充數據後並下載到客戶端
@RequestMapping("buildWordDoc")
public void buildWordDoc(String id,HttpServletResponse response){
Path templatePath = Utils.getClassFileRealPath(this.getClass()).resolve("../export").normalize().toAbsolutePath();//模板文件所在路徑
try{
response.setContentType("application/msword;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(("學生信息.doc").getBytes(), "iso8859-1"));
Student stu = studentService.get(id);
Map<String, Object> beans = new HashMap<String, Object>();//用於存儲需要填充的數據
beans.put("student",stu);
WordAndExcelUtil.mxl2Word(templatePath , "template.xml", response.getWriter(), map);
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
//填充數據生成文檔後,並進行上傳到業務信息中
public void buildReceiveDoc(String id) throws IOException {
Student student = studentService.get(id);
Map<String, Object> beans = new HashMap<String, Object>();
beans.put("student ",student );
File tempFile = null;
Writer out = null;
try{
String strPath = SysVariable.get("YIDA_FILE") + "/temp";//臨時文件的目錄
String tempFileName = "資料領取單" + StringUtils.uuid()+".doc";
tempFile = new File(strPath, tempFileName);//填充好的臨時文件
if (!tempFile.exists()) { //文件不存在則創建文件,先創建目錄
File dir = new File(tempFile.getParent());
dir.mkdirs();
tempFile.createNewFile();
}
Path templatePath = Utils.getClassFileRealPath(this.getClass()).resolve("../export").normalize().toAbsolutePath();//模板存放的路徑,根據具體情況取
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
WordAndExcelUtil.mxl2Word(templatePath,"studentInfoTemplate.xml", out, beans);
FileUploadForm uploadForm = new FileUploadForm();//上傳文件
uploadForm.setUploadFileName("學生信息" + DateUtil.format(curDate,DateUtil.DATE_FORMAT_ZERO)+ ".doc");
uploadForm.setUpload(tempFile);
fileService.upload(uploadForm);//系統的上傳功能
}finally {
if(out != null){
out.close();
}
tempFile.delete();//刪除緩存文件
}
}
對於excel.則比較方便.保留原來的格式即可.寫上佔位符 ps:excel中的佔位符是可以爲null的.
//生成文檔後並上傳到業務信息中
public void buildExcel(String id) throws Exception {
Date curDate = new Date();
Student student = studentService.get(id);
String fileName = "學生信息" + DateUtil.format(curDate,DateUtil.DATE_FORMAT_ZERO)+ ".xls";
Map<String, Object> beans = new HashMap<>();
beans.put("student ",student );
File tempFile = null;
FileOutputStream out = null;
try{
String tempDir = SysVariable.get("YIDA_ROOT") + "/temp";
String tempFileName = "概算工程彙總表" + StringUtils.uuid()+".xls";
tempFile = new File(tempDir, tempFileName);//填充好的臨時文件
if (!tempFile.exists()) { //文件不存在則創建文件,先創建目錄
File dir = new File(tempFile.getParent());
dir.mkdirs();
tempFile.createNewFile();
}
out = new FileOutputStream(tempDir + "/" + tempFileName);
Path templatePath = Utils.getClassFileRealPath(this.getClass()).resolve("../../export").normalize().toAbsolutePath();
WordAndExcelUtil.mxl2Excel(beans,templatePath + "/studentInfoTemplate.xls", out);
AuditAchieveDoc doc = auditAchieveDocService.createIfAbsent("學生信息"",cost.getId());
FileUploadForm fileForm = new FileUploadForm();
fileForm .setUpload(Arrays.asList(tempFile));
fileService.upload(uploadForm);
}finally {
if(out != null){
out.close();
}
tempFile.delete();//刪除緩存文件
}
}
另外附上WordAndExcelUtil工具類
public class WordAndExcelUtil {
public static void mxl2Excel(Map<String, Object> excelBeans,String templatePath, OutputStream os) throws Exception {
XLSTransformer transformer = new XLSTransformer();
FileInputStream fis = new FileInputStream(templatePath);
InputStream is = new BufferedInputStream(fis);
Workbook hssfWorkbook = transformer.transformXLS(is, excelBeans);
hssfWorkbook.write(os);
}
public static void mxl2Word(Path directory,String filename,Writer writer,Map<String, Object> map) throws IOException {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setDefaultEncoding("UTF-8");
configuration.setDirectoryForTemplateLoading(directory.toFile());
Template template=configuration.getTemplate(filename);
try {
template.process(map, writer);
} catch (TemplateException e) {
e.printStackTrace();
}
}
}