各位好,本人尝试采用Jxls2通过spring mvc方式导出并下载Excel文件,文件能下载,但是下载下来的文件提示文件已损坏,点击进去出现内容乱码。但是尝试

OutputStream os = new FileOutputStream(new File("D:"+File.separator+"test111.xls"));

是能正常导出excel数据的,不知是否有人遇到过同样的问题,代码如下

package com.example.demo;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
public class JxlsExcelView extends AbstractView {
    private static final String CONTENT_TYPE = "application/vnd.ms-excel";
    private String templatePath;
    private String exportFileName;
     * @param templatePath   模版相对于当前classpath路径
     * @param exportFileName 导出文件名
    public JxlsExcelView(String templatePath, String exportFileName) {
        this.templatePath = templatePath;
        if (exportFileName != null) {
            try {
                exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
        this.exportFileName = exportFileName;
        setContentType(CONTENT_TYPE);
    @Override
    protected void renderMergedOutputModel(
            Map<String, Object> model,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Context context = new Context(model);
        response.setContentType(getContentType());
        response.setHeader("content-disposition",
                "attachment;filename=" + exportFileName + ".xls");
        ServletOutputStream os = response.getOutputStream();
        //OutputStream os = new FileOutputStream(new File("D:"+File.separator+"test111.xls"));
        InputStream is = getClass().getClassLoader().getResourceAsStream(templatePath);
        JxlsHelper.getInstance().processTemplate(is, os, context);
        is.close();

链接为测试代码源码

http://p59his853.bkt.clouddn.com/demo.zip

项目跑起来后打开http://localhost:8080/swagger-ui.html,点击接口try it out即可测试

看看你的target里面的excel是否能打开,因为maven在你编译的 时候可能会把你的那个excle格式弄乱了.在maven的build里面加上类似于以下的代码

<resources>
	<resource>
		<directory>src/main/resources</directory>
		<filtering>true</filtering>
		<excludes>
			<exclude>**/*.xlsx</exclude>
		</excludes>
	</resource>
	<resource>
		<directory>src/main/resources</directory>
		<filtering>false</filtering>
		<includes>
			<include>**/*.xlsx</include>
		</includes>
	</resource>
</resources>

然后再去试试

评论 (0)