Reading Excel in C# - Dataset, IExcelReader

时间:2016-10-20 19:43:32

标签: c# vba dataset

Good day,

Below is my starting attempt at copying some stuff I have in VBA into C#. I realize there are many ways to skin a cat in coding an I am new to this.

I need C# to open 2 files, run some functions on one (index, match, sumif, etc) and read from another. I have another function working just fine with dataset but one of the things I need to do is unmerge some cells in order to read its contents. Below is a snippet of VBA I need to copy for example in c#. How do I do this?

    public void getEMSComparison(string filePath)
    {
        FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
        FileStream stream1 = File.Open(@"W:\Becoding.xlsx", FileMode.Open, FileAccess.Read);


        IExcelDataReader excelReader;
        IExcelDataReader excelReader1;
        if (Path.GetExtension(filePath).ToUpper() == ".XLS")
        {

           excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            excelReader1= ExcelReaderFactory.CreateOpenXmlReader(stream1);
        }
        else
        {

            excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            excelReader1 = ExcelReaderFactory.CreateOpenXmlReader(stream1);
        }


        while (excelReader.Read() & excelReader1.Read())
        {
            DataSet result = excelReader.AsDataSet();
            DataSet result1 = excelReader1.AsDataSet();
            excelReader.IsFirstRowAsColumnNames = false;
            excelReader1.IsFirstRowAsColumnNames = false;

            Console.WriteLine(result.Tables[0].Rows.Count); //count number of rows
            Console.WriteLine(result.Tables[0].Columns.Count); // count number of rows
            MessageBox.Show(result1.Tables[0].Rows[1][0].ToString()); //1A in construction 

        }
        excelReader.Close();
        excelReader1.Close();
    }

VBA

With wb2.Sheets(1) 'find where total is, have to unmerge to view it
   .Range("A:A").UnMerge
   firstrow = .Range("A:A").Find(what:="Total", after:=.Range("A1")).MergeArea.Cells(1, 1).Row + 1
End With

0 个答案:

没有答案