Java 下载 Excel文件打不开

public static String downloadFile(HttpServletResponse response, String fileName, String templatePath) {
    response.setHeader("content-type", "application/octet-stream");
    // 如果下载的文件是固定的,那么指定文件类型
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    try {
        fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

    } catch (UnsupportedEncodingException e2) {
        e2.printStackTrace();
    }
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        os = response.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(new File(templatePath + fileName));
        // 修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容?如果信任此工作簿的来源,请点击"是"
        
        response.setHeader("Content-Length", String.valueOf(fileInputStream.getChannel().size()));
        bis = new BufferedInputStream(fileInputStream);
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (FileNotFoundException e1) {
        return "系统找不到指定的文件";
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

你可能感兴趣的:(java,poi,excel,java)