Hello.
I’m trying to do a conversion of a very simple excel to word. The excel is a valid one and it opens without any issue in Microsoft Excel, but whenever I try to convert it with aspose (using 23.1 version of both aspose-cells and aspose-words) I get the following exception:
com.aspose.words.FileCorruptedException: The document appears to be corrupted and cannot be loaded.
I’ve traced this to the single cell in the SQL sheet that contains the text of an sql. Please find the excel attached:SqlResultTest.zip (6.8 KB)
Here is the code I use to convert the excel (and append it to a word document):
private void appendExcelDocument(Document wordDocument, MultipartFile file) { try (ByteArrayOutputStream conversionStream = new ByteArrayOutputStream()){ // Load the Excel file var workbook = new Workbook(new ByteArrayInputStream(file.getBytes())); // For each sheet set up the page orientation and the cells size for (int i = 0; i < workbook.getWorksheets().getCount(); i++ ) { workbook.getWorksheets().get(i).getPageSetup().setOrientation(PageOrientationType.LANDSCAPE); workbook.getWorksheets().get(i).getPageSetup().setFitToPagesWide(1); workbook.getWorksheets().get(i).getPageSetup().setFitToPagesTall(0); } // Create the output stream to save the Excel conversion to word workbook.save(conversionStream, com.aspose.cells.SaveFormat.DOCX); var docAttachment = new Document(new ByteArrayInputStream(conversionStream.toByteArray())); // Dont copy the footers/headers from the target document in case they are already defined disableHeadersLink(docAttachment); // Remove any "empty" paragraphs the document may have in the end removeLastParagraph(docAttachment); List<Table> tables = Arrays.stream(docAttachment.getChildNodes(NodeType.TABLE, true).toArray()) .filter(Table.class::isInstance) .map(Table.class::cast) .collect(Collectors.toList()); for (Table table: tables) { table.autoFit(AutoFitBehavior.AUTO_FIT_TO_WINDOW); } wordDocument.appendDocument(docAttachment, ImportFormatMode.KEEP_SOURCE_FORMATTING); } catch (IOException e) { throw new RuntimeException("Could not read content from file " + file.getName() + ". Error: " + e); } catch (Exception e) { throw new RuntimeException("Could not create Aspose Excel document from file " + file.getName() + ". Error: " + e); } } private void disableHeadersLink(Document wordDocument) { // Disable headers/footers inheriting. wordDocument.getFirstSection().getHeadersFooters().linkToPrevious(false); } private void removeLastParagraph(Document wordDocument) { // Get the last paragraph in the document. Paragraph lastPara = wordDocument.getLastSection().getBody().getLastParagraph(); // Remove last run in the paragraph if it contains page break. if (lastPara.getRuns().getCount() > 0) { Run lastRun = lastPara.getRuns().get(lastPara.getRuns().getCount() - 1); if (lastRun.getText().equals(ControlChar.PAGE_BREAK)) lastRun.remove(); } }
Thank you.