gpt4 book ai didi

java - 将扩展名为 .xls 但另存为 xml 电子表格 2003 的文件转换为 .xls 文件格式

转载 作者:行者123 更新时间:2023-12-01 22:59:55 27 4
gpt4 key购买 nike

我有一个文件 .XLS 扩展名,但保存为 XMl 电子表格 2003 ,想要读取该文件并使用 java 代码将其转换为 .XLS 扩展名,我的代码如下 -

公共(public)类 ExcelImport {

public boolean readStream(InputStream stream) throws InvalidFormatException {
boolean success;

try {
byte[] bytes = getBytes(stream);
InputStream wrappedStream = new ByteArrayInputStream(bytes);

Workbook workbook = WorkbookFactory.create(wrappedStream);
//XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(wrappedStream.toString()));
for (int i = 0; i <workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);
for (Row row : sheet) {
IterateThroughRow(row);
}
}
success = true;
} catch (FileNotFoundException e) {
success = false;
e.printStackTrace();
} catch (IOException e) {
success = false;
e.printStackTrace();
}
return success;
}

private void IterateThroughRow(Row row) {
Iterator<Cell> cellIterator = row.cellIterator();

while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();

switch (cell.getCellType()) {
//do something with the content...
case Cell.CELL_TYPE_STRING:
cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
cell.getBooleanCellValue();
break;
default:
}
}
}

public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int len;
byte[] data = new byte[100000];
while ((len = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, len);
}

buffer.flush();
return buffer.toByteArray();
}

public static void main(String[] args) throws InvalidFormatException, IOException {

ExcelImport excelImport = new ExcelImport();
InputStream is = new FileInputStream("C:/Users/Desktop/Test.xls");
excelImport.readStream(is);

}}

但是当我运行时它会给出如下错误 -

线程“main”中出现异常java.lang.IllegalArgumentException:您的InputStream既不是OLE2流,也不是OOXML流 在 org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:75)

最佳答案

您可以尝试运行文件路径| hexdump -n 8 -e 确保文件确实如其所说。从异常情况来看,POI 似乎无法理解该文件格式。

关于java - 将扩展名为 .xls 但另存为 xml 电子表格 2003 的文件转换为 .xls 文件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58426447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com