springboot下载excel模板,excel表损坏数据错误

问题

在maven编译时excel模板表就已经被损坏了,下载一个已经被损坏的Excel表肯定是无法正常打开的,数据乱码错误

为啥Excel表在编译后会被损坏,这里就涉及到maven resource标签的使用。

pom.xml 添加

springboot下载excel模板,excel表损坏数据错误_第1张图片
将excel格式文件排除,避免造成编译导致excel文件损坏

	<build>
        <finalName>sim-apifinalName>
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
                <excludes>
                    <exclude>**/*.xlsexclude>
                    <exclude>**/*.xlsxexclude>
                excludes>
                <filtering>truefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.xlsinclude>
                    <include>**/*.xlsxinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <mainClass>com.gaolei.sim.ApplicationmainClass>
                    <layout>JARlayout>
                configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackagegoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>

控制器

@RequestMapping(value = "/download", method=RequestMethod.POST, produces = { "application/json;" })
    @ApiOperation(value = "下载风险研判信息记录模板", httpMethod = "POST", notes = "下载风险研判信息记录模板")
    public void download(HttpServletResponse res, HttpServletRequest req) throws Exception{
    String fileName ="设备导出.xls";
    String filePath = getClass().getResource("/static/" + fileName).getPath();
    filePath = URLDecoder.decode(filePath, "UTF-8");
    OutputStream os = res.getOutputStream();
    InputStream in =new FileInputStream(filePath) ;
    //InputStream in = getClass().getClassLoader().getResourceAsStream("/static/"+fileName);

    res.setHeader("Content-Length", String.valueOf(in.available()));
    res.setContentType("multipart/form-data");
    res.addHeader("Content-Disposition","attachment;fileName=" + new String(fileName.getBytes("GBK"),"UTF-8"));
    IOUtils.copy(in,os);
    os.flush();
    }

参考文章: https://blog.csdn.net/qq_42270377/article/details/92771349

你可能感兴趣的:(SpringBoot)