【发布时间】:2012-02-14 15:22:36
【问题描述】:
我有一个奇怪的问题:我有一个 CSV 文件,我可以用记事本和 MS Excel 2010 正确读取。
我尝试使用以下代码读取此文件的行:
BufferedReader source = new BufferedReader(new FileReader(fileName));
String currentRow = null;
while (null != (currentRow=source.readLine())){
System.outprintln(currentRow)
}
当程序运行时,我只读取二进制字符,并且行的长度与实际不同(我预计行有 2000 个字符,但我发现 55 个字符或 1 个字符)。
我在 Eclipse 中工作:如果我用 文本编辑器打开这个 CSV 文件,我会读到奇怪的字符,当我用 系统编辑器打开它时,我会在 MS 中读到正确的值Excel。
此文件的类型是Microsoft Excel 逗号分隔值的文件:此文件是否包含一些二进制字符?
我尝试通过以下代码使用 Apache POI(读取 CSV 和 XLS 中的文件):
public void displayFromExcel (String xlsPath){
POIFSFileSystem fileSystem = null;
try{
fileSystem = new POIFSFileSystem (new FileInputStream (xlsPath));
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
HSSFSheet sheet = workBook.getSheetAt (0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext ()){
HSSFRow row = (HSSFRow) rows.next ();
System.out.println ("Row No.: " + row.getRowNum ());
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext ()){
HSSFCell cell = (HSSFCell) cells.next ();
System.out.println ("Cell No.: " + cell.getCellNum ());
switch (cell.getCellType ()){
case HSSFCell.CELL_TYPE_NUMERIC :
System.out.println ("Numeric value: " + cell.getNumericCellValue ());
break;
case HSSFCell.CELL_TYPE_STRING :
HSSFRichTextString richTextString = cell.getRichStringCellValue ();
System.out.println ("String value: " + richTextString.getString ());
break;
default :
System.out.println ("Type not supported.");
break;
}
}
}
} catch (IOException e) {
e.printStackTrace ();
}
}
它不工作,我在控制台收到这条消息:
java.io.IOException: Invalid header signature; read 0x003000310030FEFF, expected 0xE11AB1A1E011CFD0
at org.apache.poi.poifs.storage.HeaderBlockReader.<init>(HeaderBlockReader.java:125)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:153)
当它运行这条指令时:
POIFSFileSystem fileSystem = new POIFSFileSystem (new FileInputStream (xlsPath));
我尝试使用库 datafile 和 Java I/O(DataInputstream 等),但没有成功。
有解决方案的想法吗?
【问题讨论】:
-
根据您发布的错误,我猜您的 Excel 文件标题不正确
-
0xfffe 是一些 unicode 标头附加到某些文本文件中。
标签: java excel csv apache-poi