如何在.Net2.0中比较两个excel表?

时间:2011-06-13 12:09:49

标签: .net excel vba c#-2.0

我有两个文本文件(这是一个逗号分隔的文件)。这两个文件的模板如下所示。

            SD,CurrentDate,RecordCount
    NI,FirstName,LastName,Place,Language
    EQ,Degree,University,Year,Aggregate
    ED,CurrentDate,RecordCount

第一个文件中的数据 - one.txt

          SD,13/06/2010,6
          NI,Rajesh,kumar,xxxx,english
          EQ,X,Stateboard,2004,75
          EQ,XII,Stateboard,2006,85
          EQ,B.E,Oxford,2008,79
             ED,13/06/2010,6

第二个文件中的数据 - Second.txt

          SD,13/06/2010,6
          NI,Rajesh,kumar,,english
          EQ,X,,2004,75
          EQ,XII,Stateboard,2006,
          EQ,,Oxford,2008,79
          ED,13/06/2010,6

现在我已将one.txt的值填充到Excel工作表(Output.xls)的“sheet1”中,然后我填充了

使用.Net代码将Second.txt的值设置为Excel工作表(Output.xls)的“sheet2”。

现在我想比较两张数据并填充“sheet3”中的差异。

“Sheet3”的o / p将有。

    Cell1       Cell2           Cell3           Cell4       Cell5
    SD:True     CurrentDate:True    RecordCount:True
    NI:True     FirstName:True      LastName:True       Place:False   Language:True
    EQ:True     Degree:True     University:False    Year:True   Aggregate:True
    EQ:True     Degree:True     University:True     Year:True   Aggregate:False
    EQ:True     Degree:False        University:True     Year:True   Aggregate:True
    SD:True     CurrentDate:True    RecordCount:True

我如何比较这两张纸?是否有可能通过VBA?我可以在.Net中调用VBA代码吗?请有人向我提供解决方案吗?

1 个答案:

答案 0 :(得分:0)

在您手动或以戏剧性方式填充值后,您似乎想要比较2张。在这种情况下,以下代码将完成这项工作,但您必须修改将在布尔值之前插入列名的部分

Dim objEX as new Excel.Application
    objEX.Visible = True
    ' Optional if you want to see what is
    ' going on in EXCEL while your code is being executed.


objEX.Workbooks.Open "C:\My Files\Filename.xls"
'Make sure you put the right path of the excel workbook you want to open

With objEX
    .Sheets(1).Activate
    .Range("a1").Select

    .Sheets(2).Activate
    .Range("a1").Select

    .Sheets(3).Activate
    .Range("a1").Select


    'assuming the populated data starts at Cell A1
    For i = 0 To 6      'because you have 6 rows
        For j = 0 To 5  'because you have 5 columns
            If .Sheets(1).ActiveCell.Offset(i, j).Value = .Sheets(2).ActiveCell.Offset(i, j).Value Then
                .Sheets(3).ActiveCell.Offset(i, j).Value = "True"
            Else
                .Sheets(3).ActiveCell.Offset(i, j).Value = "False"
            End If
        Next
    Next


    .ActiveWorkbook.Save
    'Saves the changes you have done

    .ActiveWorkbook.Close
    'Closes the workbook


    .Quit
    'Quits excel instance and releases the process from task manager

End With

    Set objEX = Nothing
    'Garbage Collection and making sure memory is released to other processes.