首页 >> 大全

解决poi导出Excel文件打开警告(一)

2023-08-06 大全 26 作者:考证青年

项目中需要导出Excel报表,使用poi导出Excel文件,添加依赖

org.apache.poipoi-ooxml3.15

org.apache.poipoi3.15

org.apache.poipoi-ooxml-schemas3.15

cn.afterturneasypoi-base3.2.0

cn.afterturneasypoi-web3.2.0

cn.afterturneasypoi-annotation3.2.0

导出文件到本地之后打开文件没有问题,上传到服务器之后,从服务器下载重新打开会弹出警告:

发现“XXX.xlsx”中的部分内容有问题。是否让我们尽量尝试恢复?如果您信任此工作簿的源,请单击“是”。

点击 “否”就不打开文件了,点击 “是”之后可以打开文件,出现以下提示:

通过修复或删除不可读取的内容,Excel 已能够打开该文件。

从网上查找原因发现:上传文件中包含大量的多余字符。发现在读取本地保存的文件上传服务器时:

public static byte[] fileToByteArray(File file) throws IOException {ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());BufferedInputStream bin = null;try {bin = new BufferedInputStream(new FileInputStream(file));byte[] buffer = new byte[1024];while (bin.read(buffer) > 0) {bos.write(buffer);}return bos.toByteArray();} finally {try {bos.close();} catch (IOException e) {e.printStackTrace();}try {bin.close();} catch (IOException e) {e.printStackTrace();}}
}

这种方式读取的文件会比真实的文件数据大

_导出时发生错误_导出此文件时出错

修改为每次读取真实的文件数据:

public static byte[] fileToByteArray(File file) throws IOException {ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());BufferedInputStream bin = null;try {bin = new BufferedInputStream(new FileInputStream(file));byte[] buffer = new byte[1024];int readCount;while((readCount = bin.read(buffer)) >0){bos.write(buffer,0,readCount);}return bos.toByteArray();} finally {try {bos.close();} catch (IOException e) {e.printStackTrace();}try {bin.close();} catch (IOException e) {e.printStackTrace();}}
}

发现相同文件不同方式读取的大小不相同。因为第一种方式读取了多余的脏数据。

修改完成之后会读取真实的文件数据,上传到服务器上之后重新下载不会弹出警告信息。

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了