java - 将扩展名为 .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 流
解决方案
您可以尝试运行文件路径| hexdump -n 8 -e以确保文件实际上是它所说的。从异常看来,POI 似乎无法理解文件格式。
推荐阅读
- c - 测试非阻塞 UDP 套接字时中止进程
- express - 数组自行填充
- php - Yii2:应用程序无法执行。Apache 显示“索引”
- javascript - 如何编写通过在一个链式惯用承诺中将文件写入云存储桶来响应数据变化的firebase云功能?
- php - Redis 会话 disable_locking 为 true
- unity3d - 如何正确使用 UNET
- ssas - 在 PowerBI 中合并来自多个 SSAS 多维数据集的数据
- wagtail - 如何迭代模板中的“页面”对象的属性?
- python - 图中的强连接组件 - networkx 库
- android - Android 应用在 onClickListener 上崩溃