簡體   English   中英

比較2個Excel文件的內容

[英]Comparing the contents of 2 excel files

我有2個excel文件,我想比較內容並突出顯示差異。 例如:

第一個檔案...

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

有沒有第三方圖書館可以做到這一點? 或最好的方法是什么?

就像DaDaDom所說的那樣,Apache POI是您想要的。 您可以從此頁面下載它。 請注意,POI項目不是完全獨立的,您可能需要下載一些額外的庫。 請遵循Apache POI網站上的說明。 這是您的用法:

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

如果是新文件,則可能需要先創建圖紙才能繼續,但是在這種情況下,文件已經創建。

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

要從單元中獲取價值,請使用:

String value = cell.getStringCellValue();

但是,如果存儲在單元格中的類型為數字,則會出現錯誤。 如果使用數字:

Int value = cell.getCellValue();

這是我編寫的用於處理不同單元格數據類型的方法:

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 "";
    }
}

我希望對Apache POI的快速介紹將對您的項目有所幫助:)

根據這個問題 ,我的答案在下面部分重復。

我的項目simple-excel提供了許多Hamcrest Matchers並包裝了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)

閱讀有關它的博客文章

我將使用epplus將兩個文檔加載到數據表中,然后遍歷它們以查找差異。 根據要突出顯示差異的方式,您可以簡單地使用epplus為單元格上色並將其保存回文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM