为什么C#Match Function在Excel中的日期格式上不起作用?

时间:2019-02-14 20:29:41

标签: c# excel office-interop

尝试在日期上使用WorksheetFunction.Match(Value,Range,0)时,出现以下异常:

System.Runtime.InteropServices.COMException:
'Unable to get the Match property of the WorksheetFunction class'

如果Excel中的数字格式设置为常规(日期存储为数字),则下面的代码有效。

我当前的解决方案是将日期列设置为常规格式,并在完成后恢复为日期格式(UK)。

// using Microsoft.Office.Interop.Excel;
Microsoft.Office.Interop.Excel.Application xlApp = 
    new Microsoft.Office.Interop.Excel.Application();
xlApp.Application.Visible = true;

Workbook xlworkbook;
Worksheet xlWorkSheet;

string filepath = "C:/test.xlsx";

xlworkbook = xlApp.Workbooks.Open(filepath);
xlWorkSheet = xlworkbook.Worksheets["Sheet1"];

//xlWorkSheet.Range["C:C"].NumberFormat = "0";
//xlWorkSheet.Range["A:A"].NumberFormat = "0";

double foo = xlApp.WorksheetFunction.Match(xlWorkSheet.Range["C1"].Value,
    xlWorkSheet.Range["A:A"], 0);

//xlWorkSheet.Range["C:C"].NumberFormat = "dd/mm/yyyy";
//xlWorkSheet.Range["A:A"].NumberFormat = "dd/mm/yyyy";

Console.Write(foo);
Console.ReadKey();
xlworkbook.Close(false);
xlApp.Quit();

0 个答案:

没有答案