poi进行word和excel文档导出

业务场景: 根据给定的模板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();
		}
	}
}
发布了53 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/102619743