通过的Microsoft.Office.Interop.Excel确定Excel版本/文化版本、文化、Office、Microsoft

2023-09-02 02:05:32 作者:谁让我最酷

我怎样才能做到这一点的.NET / C#?

How can I achieve that in .NET/C#?

推荐答案

您可以使用此code段:(从我的一个项目中获得,所以不能保证工作的开箱即用)

You could use this code snippet: (taken from one of my projects, so not guaranteed to work out of the box)

Microsoft.Office.Interop.Excel.Application tExcel = new Application();
CultureInfo cSystemCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo cExcelCulture = new CultureInfo(tExcel.LanguageSettings.get_LanguageID(
    Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDUI));

try
{
    Thread.CurrentThread.CurrentCulture = cExcelCulture;
    double tVersion;
    bool tParseSucceded = double.TryParse(tExcel.Version, out tVersion);

    // 12 is the first version with .xlsx extension
    if (tVersion > 11.5)
        cDefaultExtension = ".xlsx";
    else
        cDefaultExtension = ".xls";

}
catch (Exception aException)
{
    cLogger.Debug("error retrieving excel version.", aException);
    cLogger.Error("error retrieving excel version.");
}
finally
{
    Thread.CurrentThread.CurrentCulture = cSystemCulture;
}