Dev*_*315 1 java excel file apache-poi
我需要返回一个工作簿,但转换为 JavaFile对象。目前我只知道如何将工作簿写入磁盘workbook.write(outputStream)。但是,我想返回该File对象,以便直接使用它进行进一步处理(上传到亚马逊)。
我的代码:
public File addErrorColumnToExcel(MultipartFile file, HashMap<Integer, String> errors, int newColumnIndex) throws IOException {
Workbook workbook = null;
Sheet sheet = null;
Row row;
Cell newErrorCell;
String errorText;
try {
workbook = new XSSFWorkbook(new BufferedInputStream(file.getInputStream()));
sheet = workbook.getSheetAt(FIRST_SHEET_INDEX);
} catch (IOException e) {
logger.error("cannot get the file: " + file.getOriginalFilename() + e);
}
//do some logic
return workbook; //but I need to convert this to a java File
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个临时文件并将数据写入该文件,然后再返回该文件。处理后不要忘记删除文件。这是一个简化的片段:
public File getEmptyExcelFile() throws IOException {
try (Workbook workbook = new XSSFWorkbook()) {
workbook.createSheet("test"); // do some logic
File outputFile = File.createTempFile("temp", ".xlsx");
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
workbook.write(fos);
}
return outputFile;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我将 try-with-resources 用于XSSFWorkbook和FileOutputStream。
另一个想法是返回一个字节数组byte[]而不是File. 这是一个更干净的解决方案,不会将文件写入磁盘。
public byte[] getEmptyExcelFileAsBytes() throws IOException {
try (Workbook workbook = new XSSFWorkbook()) {
workbook.createSheet("test"); // do some logic
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
return baos.toByteArray();
}
}
Run Code Online (Sandbox Code Playgroud)