解决poi导出Excel文件打开警告(一)
项目中需要导出Excel报表,使用poi导出Excel文件,添加依赖
org.apache.poi poi-ooxml 3.15
org.apache.poi poi 3.15
org.apache.poi poi-ooxml-schemas 3.15
cn.afterturn easypoi-base 3.2.0
cn.afterturn easypoi-web 3.2.0
cn.afterturn easypoi-annotation 3.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();}}
}
发现相同文件不同方式读取的大小不相同。因为第一种方式读取了多余的脏数据。
修改完成之后会读取真实的文件数据,上传到服务器上之后重新下载不会弹出警告信息。