我正在使用 apache POI 读取 xlsx 文件并将数据上传到数据库中。我必须在 Jboss 上运行的调度程序(在预定时间)中完成这项工作。由于调度程序在与上传的一个文件不同的服务器上运行,我使用 postgres bytea 数据类型使用以下代码将文件保存在数据库中 PreparedStatement ps = con.prepareStatement( "UPDATE tk_tablename SET tk_filecolumnname = ? WHERE primarykey = '" + fileAttachment.getPrimaryKey() + "';");
FilePathAssociation filePathAssociation = fileAttachment.getFilePathAssociation();
if ( filePathAssociation != null )
{
File blobFile = new File( filePathAssociation.getPhysicalFilePath() );
FileInputStream fis = new FileInputStream( blobFile );
ps.setBinaryStream( 1, fis, (int)blobFile.length() );
ps.executeUpdate();
ps.close();
fis.close();
}
这工作正常,文件保存在数据库中。
但是在使用下面的代码读取服务器上的文件时
ResultSet rs =
stmt.executeQuery( "SELECT tk_filecolumnname FROM tk_tablename WHERE primarykey = '"
+ fileAttachment.getPrimaryKey() + "';" );
if ( rs != null && rs.next() )
{
InputStream fileInputStream = rs.getBinaryStream( 1 );
Workbook workbook = WorkbookFactory.create( fileInputStream ); // apache POI code to read a xlsx file.
rs.close();
return file;
}
出现以下错误,
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
我知道要读取 xlsx 文件,POI 需要由 OOXML 支持的流。但是为什么
ResultSet.getBinaryStream()
方法没有返回创建文件时保存的相同输入流。
请帮助或分享您的知识。
谢谢, 阿米特。
最佳答案
执行以下操作:
1) 断言您的代码正在从文件中正确读取工作簿(只需打开 FileInputStream)。
2) 一旦您的代码正在处理文件,而不是来自数据库的流,它可能与库处理流的方式有关。您可以尝试将整个流保存到临时文件中,这给您带来了额外的优势,您可以更快地释放数据库连接。
关于java - 无法使用 apache POI 读取保存在 postgres 数据库(作为 bytea)中的 xlsx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7333743/