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

问题描述 投票:0回答:2

我有一个.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流,也不是OOXML流在org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:75)

java java-ee apache-poi jxl
2个回答
0
投票

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


0
投票

[Hi Amol已经说过它的XMl电子表格2003,但另存为.xls扩展名。 POI无法理解我所知道的格式,但是如果我打开该文件并再次将其另存为.xml,它如何工作就很好了,但是我不想手动执行它,所以我想用Java代码来实现。

© www.soinside.com 2019 - 2024. All rights reserved.