首页 > 解决方案 > 将扩展名为 .xls 但另存为 xml 电子表格 2003 的文件转换为 .xls 文件格式

问题描述

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

公共类 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);

} }

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

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

标签: javajakarta-eeapache-poijxl

解决方案


您可以尝试运行文件路径| hexdump -n 8 -e以确保文件实际上是它所说的。从异常看来,POI 似乎无法理解文件格式。


推荐阅读