Error when exporting data to excel in c# (win form

2019-08-25 00:59发布

When trying to export data from DataGridView to excel System.ComponentModel.Win32Exception: 'The specified executable is not a valid application for this OS platform.' exception is thrown, funny thing is that file is saved like supposed to. I fought that this is because I reinstalled packages for entire solution, but it's not the case.

Exception occurs when trying to call Process.Start(fileName) method, where the value of fileName is: C:\\Users\\net\\Desktop\\Excel TESTING\\OperatorStatisticsData.xlsx

Note that my application is running on any CPU( 32 or 64 bit), and I am currently running win10 64 bit operating system. enter image description here Any suggestion how to fix this?

1条回答
贪生不怕死
2楼-- · 2019-08-25 02:00

Try to call EXCEL.EXE directly (change path if need to):

string filePath = @"c:\Temp\export.XLSX";
// For me this generates: C:\\Program Files\\Microsoft Office\\Office14\\EXCEL.EXE
var exec = System.IO.Path.Combine(
                Environment.GetEnvironmentVariable("ProgramW6432"),
                "Microsoft Office", "Office14", "EXCEL.EXE");
Process.Start(fileName: exec, arguments: filePath);

UPDATE

You can obtain executable file by using Shell AssocQueryString function, which retrieves (amongst other properties) executable file associated with extension. Here's the method on C# which makes use of it:

[Flags]
public enum AssocF
{
    Init_NoRemapCLSID = 0x1,
    Init_ByExeName = 0x2,
    Open_ByExeName = 0x2,
    Init_DefaultToStar = 0x4,
    Init_DefaultToFolder = 0x8,
    NoUserSettings = 0x10,
    NoTruncate = 0x20,
    Verify = 0x40,
    RemapRunDll = 0x80,
    NoFixUps = 0x100,
    IgnoreBaseClass = 0x200
}

public enum AssocStr
{
    Command = 1,
    Executable,
    FriendlyDocName,
    FriendlyAppName,
    NoOpen,
    ShellNewValue,
    DDECommand,
    DDEIfExec,
    DDEApplication,
    DDETopic
}

public static class FileAssocHelper
{

    [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, [In][Out] ref uint pcchOut);

    public static string FileExtensionInfo(AssocStr assocStr, string doctype)
    {
        uint pcchOut = 0;
        AssocQueryString(AssocF.Verify, assocStr, doctype, null, null, ref pcchOut);
        StringBuilder pszOut = new StringBuilder((int)pcchOut);
        AssocQueryString(AssocF.Verify, assocStr, doctype, null, pszOut, ref pcchOut);
        return pszOut.ToString();
    }

}

Now we can retrieve executable file and open Excel file:

string filePath = @"c:\Temp\Results.xlsx";
string exec = FileAssocHelper.FileExtensionInfo(AssocStr.Executable, ".xlsx");
Process.Start(exec, filePath);
查看更多
登录 后发表回答