【问题标题】:Apache POI reading xlsx inputstream issueApache POI 读取 xlsx 输入流问题
【发布时间】:2017-10-14 12:00:41
【问题描述】:

请忽略这个问题:愚蠢的解析错误。

我有一个 API,它允许上传文件并使用 Apache POI 读取它(如果文件类型不是 .xlsx,则抛出异常)。但是,似乎 WorkbookFactory.create(inputstream) 没有生成正确的文件。当我在代码中读取文件时,我在读取应该存在数据的单元格时得到null 值。 代码如下:

     @POST
        @Path("<path>")
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        @Produces(MediaType.APPLICATION_JSON)
        public Response submitFile(@FormDataParam("file") InputStream uploadedInputStream,
                                         @FormDataParam("file") FormDataContentDisposition fileDetail verticalId) {
            try {
                StringBuilder fileNameBuilder = new StringBuilder();
                String[] names = fileDetail.getFileName().replace(" ", "_").split("\\.");

                Contents contents = fileParser.parse(uploadedInputStream);

            return Response.ok().build();
        }

public class XlsxParser implements FileParser {

    public Content parse(File file) throws IOException InvalidFileFormatException{
         Content content = new Content();

        Workbook file;
        try {
            designFile = WorkbookFactory.create(file);
        } catch (InvalidFormatException exception) {
            throw new InvalidFileFormatException("Invalid file format. Expected file type is .xlsx");
        }
        Sheet sheet = file.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.rowIterator();
        Row row = rowIterator.next();
        int cellCount = row.getPhysicalNumberOfCells();
        return content;
    }
} 

如果我首先从inputstream 创建一个.xlsx 文件,然后将File 对象传递给WorkbookFactory.create(),则相同的代码可以正常工作

有人遇到过同样的问题吗?感谢您的帮助。

【问题讨论】:

    标签: java apache-poi dropwizard


    【解决方案1】:

    我之前也遇到过类似的问题。我所做的只是拒绝使用Workbook.create(InputStream inp) 方法。据我所知,这种方法即将被弃用。 The official documentation 告诉你:

    1. Workbook.create(InputStream inp) 消耗的内存比Workbook.create(File file) 多。这就是为什么使用第二种方法要好得多。

    2. Workbook.create(InputStream inp) 需要inp 来支持marking and reseting 或被包裹到PushbackInputStream 中。这不是很棘手,但是如果我们可以从InputStream 创建一个新的File 并使用更节省内存的方法,为什么要这样做?

    3. 为了正确释放资源,Workbook 应在使用后关闭。使用Workbook.create(File file) 也需要这个,所以在这里使用Workbook.create(InputStream inp) 没有任何好处。

    4. 毕竟,Apache POI 的作者建议尽可能使用Workbook.create(File file) 方法而不是Workbook.create(InputStream inp)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多