java.io.EOFException: неожиданный конец входного потока ZLIB с использованием Apache POI - PullRequest
0 голосов
/ 18 сентября 2018

Я пытаюсь создать сводную таблицу Excel, используя Apache POI.
В тот момент, когда я пытаюсь записать данные в рабочую книгу workbook.write(fileOut);, я получаю исключение

org.apache.poi.ooxml.POIXMLException: java.io.EOFException: Неожиданный конец входного потока ZLIB

Существует код класса:

public class PivotTable {



public static void createPivotTable(String pathToWorkbook, String sheetName) throws IOException {

    Workbook workbook = new XSSFWorkbook(pathToWorkbook);

    XSSFSheet sheet = (XSSFSheet) workbook.getSheet(sheetName);

    int firstRowInd = sheet.getFirstRowNum();
    int lastRowInd = sheet.getLastRowNum();
    int firstCellInd = sheet.getRow(0).getFirstCellNum();
    int lastCellInd = sheet.getRow(0).getLastCellNum() - 1;

    //Specifying top left ant the bottom right of the table data
    CellReference topLeft = new CellReference(firstRowInd, firstCellInd);
    CellReference botRight = new CellReference(lastRowInd, lastCellInd);

    //The area of data in table
    AreaReference aref = new AreaReference(topLeft, botRight, SpreadsheetVersion.EXCEL2007);

    //Position of the pivot table
    CellReference pos = new CellReference(firstRowInd + 4, lastCellInd + 1);

    //Creating the pivot table
    XSSFPivotTable pivotTable = sheet.createPivotTable(aref, pos);


    pivotTable.addRowLabel(0);
    pivotTable.addRowLabel(2);
    pivotTable.addColLabel(3);

    FileOutputStream fileOut = new FileOutputStream(pathToWorkbook);
    workbook.write(fileOut);
    fileOut.close();


}

И существует StackTrace of Exception:

Исключение в потоке "main" org.apache.poi.ooxml.POIXMLException: java.io.EOFException: неожиданный конец входного потока ZLIB
в org.apache.poi.ooxml.POIXMLDocument.getProperties (POIXMLDocument.java:147)
в org.apache.poi.ooxml.POIXMLDocument.write (POIXMLDocument.java:240)
в PivotTable.createPivotTable (PivotTable.java): at50Main.main (Main.java:14) Причина: java.io.EOFException: неожиданный конец входного потока ZLIB
в java.util.zip.InflaterInputStream.fill (InflaterInputStream.java:240)
в организации.apache.commons.compress.archivers.zip.InflaterInputStreamWithStatistics.fill (InfLaterInputStreamWithStatistics.java:52)
в java.util.zip.InflaterInputStream.read (InflaterInputStream.java:158)
в org.apache.commons.compress.archivers.zip.InflaterInputStreamWithStatistics.read (InflaterInatistics.ream67)
в java.util.zip.InflaterInputStream.read (InflaterInputStream.java:122)
в org.apache.commons.compress.archivers.zip.InflaterInputStreamWithStatistics.read (InflaterInputStreamWithStatistics.java:58) * 25* at java.io.FilterInputStream.read (FilterInputStream.java:83)
at org.apache.poi.openxml4j.util.ZipArchiveThresholdInputStream.read (ZipArchiveThresholdInputStream.java:69)
на com.sun.org.apache.xerces.internal.impl.XMLEntityManager $ RewindableInputStream.read (XMLEntityManager.java:2890)
в com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity (XMLEjava) 67* at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion (XMLVersionDetector.java:148)
в com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse (XML11Configuration.java:805)
в com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse (XML11Configuration.java: 770)
в com.sun.org.apache.xerces.internal.parsers.XMLParser.parse (XMLParser.java:141)
в com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse (AbstractSAXParser.java:1213)
на com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl $ JAXPSAXParser.parse (SAXParserImpl.java:643)
в org.apimp.xbe.store.Locale $ SaxLoader.load (Locale.java:3414)
в org.apache.xmlbeans.impl.store.Locale.parseToXmlObject (Locale.java:1272)
в org.apache.xmlbeans.impl.store.Locale..extendedProperties.PropertiesDocument $ Factory.parse (Неизвестный источник)
в org.apache.poi.ooxml.POIXMLProperties. (POIXMLProperties.java:81)
at org.apache.poi.ooxml.POIXMLDocument.getProperties (POIXMLDocument.java:145) ... еще 3

Ответы [ 3 ]

0 голосов
/ 19 октября 2018

Кажется, есть небольшая ошибка в методе workbook.write ().Я нашел 2 обходных пути.Сначала необходимо указать любое другое (фиктивное) имя файла для FileOutputStream.Когда книга закроется, оба файла будут заполнены.Второе, и более хорошее, это указать фиктивный OutputStream для метода workbook.write ():

OutputStream dummyOutputStream = new OutputStream() {
            @Override
            public void write(int b) throws IOException {

            }
        };
        workbook.write(dummyOutputStream);
        dummyOutputStream.close();
        workbook.close();
0 голосов
/ 14 февраля 2019

У меня была та же проблема, я решил ее, изменив строку:

Workbook workbook = new XSSFWorkbook(pathToWorkbook);

на:

Workbook workbook = new XSSFWorkbook(new FileInputStream(pathToWorkbook));

Надеюсь, это поможет!:)

0 голосов
/ 18 сентября 2018

Уверен, проблема в том, что вы перезаписали файл.Попробуйте сохранить в другой путь.Если вы все еще хотите перезаписать файл, сохранить его в другом месте, удалить оригинал, а затем переименуйте файл, который вы записали, в место:

try (FileOutputStream fileOut = new FileOutputStream(pathToWorkbook + ".new")) {
    workbook.write(fileOut);
}
Files.delete(Paths.get(pathToWorkbook));
Files.move(Paths.get(pathToWorkbook + ".new"), Paths.get(pathToWorkbook));
...