Searching date string in file excel

2019-09-17 21:57发布

I'm working with an excel file and I'm trying to find the position(address) of the cells with date value like "16/02/2015" as content. In order to do this with windows Forms application I use a datetimepicker. My code is as following:

// Firstly I want a string like 16/02/2015 inserted in the datetimepicker
string date = DateTimePicker1.Value.ToString().Substring(0,10); 

        List<string> Testsdone = new List<string>();          

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(file_opened, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);


        Excel.Range currentFind = null;
        Excel.Range firstFind = null;


        Excel.Range tests = xlWorkSheet.get_Range("K13", "K2295");
                    currentFind = tests.Find(date);
        .....

I have exactly the same content "16/02/2015" written in my excel file, but the currectFind always shows null! I have no idea why the two "16/02/2015" are different. Anybody got an idea? thanks!

标签: c# excel
1条回答
一夜七次
2楼-- · 2019-09-17 22:16

Well after some investigation I found that the problem is caused by the Find function

currentFind = tests.Find(date);

which for unknown reason failed to find the date. From another post how to Search in excel file I got this method, that I changed this into:

currentFind = xlworkSheet.Cells.Find(date, Type.Missing, Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues,             Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,   Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false,Type.Missing, Type.Missing);

And it works. But I still have no idea why the Excel.Range.Find fails and Excel.workersheet.Cells.Find works

查看更多
登录 后发表回答