我正在使用grails-excel-export插件将数据导出到 Excel(xlsx 格式),但在使用 Microsoft Office 打开文件时遇到问题(使用 OpenOffice 则没有问题)。
当我打开它时,我收到消息“我们发现‘exportedFile.xlsx’中的某些内容存在问题。您希望我们尽力恢复吗?如果您信任此工作簿的来源,单击"is",与此相同:
我已经发现,只有在将任何类型的单元格样式应用于工作簿时才会出现问题,在我的例子中,我将第一行设置为粗体。
这是代码:
def exportToExcel(results, headers, properties, ByteArrayOutputStream outputStream) {
WebXlsxExporter webXlsxExporter = new WebXlsxExporter()
webXlsxExporter.setWorksheetName("Sheet")
webXlsxExporter.with {
fillHeader(headers)
add(results, properties)
save(outputStream)
}
def wb = webXlsxExporter.getWorkbook()
def row = webXlsxExporter.getSheet().getRow(0)
makeFirstRowBold(wb, row)
wb.write(outputStream)
}
def makeFirstRowBold(Workbook wb, Row row) {
CellStyle style = wb.createCellStyle()
Font font = wb.createFont()
font.setBold(true) //Already tried with font.setBoldweight(Font.BOLDWEIGHT_BOLD)
style.setFont(font)
for (int i = 0; i < row.getLastCellNum(); i++) {
row.getCell(i).setCellStyle(style)
}
}
最佳答案
如果这种情况发生在其他人身上,就会发现向输出流写入两次会以某种方式损坏文件。
因此,由于我们已经在这一行中写入输出流:
wb.write(outputStream)
我删除了这个:
save(outputStream)
而且看起来运行良好。
关于java - Grails:Excel 导出 .xlsx 样式问题,打开文件时出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542631/