Java Export Excel to solve the problem garbled and unreadable open the exported file to be restored

Import Package, would have their own I do not want to deal with the poi, persevering, do not know why they export stream will always be unreadable error, so it is still a simple point of it:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

Tools Code:

public class FileUtil {

    public static void download(String filename, HttpServletResponse res) {
        String filePath = "./template/" + filename;
        try (OutputStream os = res.getOutputStream(); InputStream bis = new BufferedInputStream(new ClassPathResource(filePath).getInputStream())){
            // 设置信息给客户端不解析
            String type = new MimetypesFileTypeMap().getContentType(filename);
            // 设置content-type,即告诉客户端所发送的数据属于什么类型
            res.setContentType(type);
            // 设置编码
            String name = URLEncoder.encode(filename, "UTF-8");

            // 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            res.setHeader("Content-Disposition", "attachment;filename=" + name);
            XSSFWorkbook workbook = new XSSFWorkbook(bis);
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}

Focusing on the phrase: XSSFWorkbook workbook = new XSSFWorkbook (bis);

Location of the file:

Published 56 original articles · won praise 75 · views 280 000 +

Guess you like

Origin blog.csdn.net/seanxwq/article/details/104774543