[英]Error when exporting data to excel in c# (win forms)
嘗試將數據從DataGridView
導出到excel System.ComponentModel.Win32Exception: 'The specified executable is not a valid application for this OS platform.'
引發異常,有趣的是,文件的保存與預期的一樣。 我之所以這么做是因為我重新安裝了整個解決方案的軟件包,但事實並非如此。
嘗試調用Process.Start(fileName)
方法時發生異常,其中fileName的值為: C:\\\\Users\\\\net\\\\Desktop\\\\Excel TESTING\\\\OperatorStatisticsData.xlsx
請注意,我的應用程序可在任何CPU(32或64位)上運行,並且當前正在運行win10 64位操作系統。 任何建議如何解決這個問題?
嘗試直接調用EXCEL.EXE
(如果需要,請更改路徑):
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
您可以使用Shell AssocQueryString函數獲取可執行文件,該函數檢索(與其他屬性一起)與擴展名關聯的可執行文件。 這是使用C#的方法:
[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();
}
}
現在我們可以檢索可執行文件並打開Excel文件:
string filePath = @"c:\Temp\Results.xlsx";
string exec = FileAssocHelper.FileExtensionInfo(AssocStr.Executable, ".xlsx");
Process.Start(exec, filePath);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.