3

我有 2 个 excel 文件,我想比较内容并突出差异。例如:

第一个文件...

name|age
abc|123
def|456
second file...
name|age
abc|123
def|456
ghi|789 - this being the differece

有没有第三方库可以做到这一点?或者最好的方法是什么?

4

3 回答 3

7

Like DaDaDom said Apache POI is what you are looking for. You can download it from this page. Mind that POI project is not fully independent and you may need to download some extra libraries. Follow the instructions on Apache POI website. This is how you use it:

InputStream myxls = new FileInputStream("workbook.xls"));
HSSFWorkbook wb = new HSSFWorkbook(myxls); // for *.xlsx use XSSFWorkbook

If it's a new file you might need to create sheet before proceeding, but in this case the files are already created.

HSSFSheet sheet = wb.getSheetAt(0);       // first sheet
HSSFRow row     = sheet.getRow(0);        // first row
HSSFCell cell   = row.getCell((short)0);  // first cell

To get value from the cell use:

String value = cell.getStringCellValue();

However if the type stored in cell is numeric you would get an error. In case of numbers use:

Int value = cell.getCellValue();

This is a method I wrote to deal with different cell data types:

public String getValue(int x, int y){
    Row row = this.activeSheet.getRow(y);
    if(row==null) return "";
    Cell cell = row.getCell(x);
    if(cell==null) return "";
    int type = cell.getCellType();
    switch(type){
    case 0:
        return cell.getNumericCellValue() + "";
    case 1:
        return cell.getStringCellValue();
    case 2:
        return cell.getCellFormula();
    case 3:
        return "";
    case 4:
        return cell.getBooleanCellValue() + "";
    case 5:
        return cell.getErrorCellValue() + "";
    default:
        return "";
    }
}

I hope this quick introduction into Apache POI will help you with your project :)

于 2012-10-08T10:25:01.933 回答
4

这个问题,我的答案部分重复如下。

我的项目simple-excel提供了一堆 Hamcrest 匹配器并包装了 Apache POI 的语法。

当您执行以下操作时,

assertThat(actual, WorkbookMatcher.sameWorkbook(expected));

例如,你会看到,

java.lang.AssertionError:
Expected: entire workbook to be equal
     but: cell at "C14" contained <"bananas"> expected <nothing>,
          cell at "C15" contained <"1,850,000 EUR"> expected <"1,850,000.00 EUR">,
          cell at "D16" contained <nothing> expected <"Tue Sep 04 06:30:00">
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)

阅读有关它的博客文章

于 2013-02-18T09:08:40.893 回答
0

我会使用 epplus 将两个文档加载到数据表中,然后遍历它们以查找差异。根据您想要突出显示差异的方式,您可以简单地使用 epplus 为单元格着色并将它们保存回文件中。

于 2012-10-08T10:11:01.223 回答