我想比较Excel文件,看看它们是否相同。我可以选择我的Excel文件并阅读它们。我有2个Excel表格,内容相同,但一个是.xls,而是.xlsx格式。
我使用以下代码来读取我的文件(对于带有HSSFWorkbook的xls等)
private String xlsx(File inputFile) {
String outputString = "";
// For storing data into String
StringBuffer data = new StringBuffer();
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
data.append(cell + ";");
}
data.append("\n");
}
System.out.println(data.toString());
outputString = data.toString();
wBook.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
return outputString;
}
在我的Excel中我有空白单元格 - 当我用xls读取它时我得到DATA;;;;;DATA
这是正确的但是当我在xlsx中执行相同操作时我得到DATA;DATA
Code以某种方式跳过空单元格?!我该如何解决这个问题? 在此先感谢
答案 0 :(得分:2)
经过一些谷歌研究和尝试不同的事情后,我找到了解决问题的方法。 Iterator跳过空单元格,因为它们没有值 - 它们是空的 - 但是在xls文件中看起来它们不是null - 无论
我的代码:
private String xlsx(File inputFile) {
String outputString = "";
System.out.println("start");
// For storing data into String
StringBuffer data = new StringBuffer();
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
// Decide which rows to process
int rowStart = 0;
int rowEnd = sheet.getLastRowNum()+1;
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = r.getLastCellNum();
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn);
if (c == null) {
data.append("" + ";");
} else {
data.append(c + ";");
}
}
data.append("\n");
}
System.out.println(data.toString());
outputString = data.toString();
wBook.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
System.out.println("end");
return outputString;
}