Excel 의 경우 여러개의 파일을 동일한 Process 가 처리하기 때문에
이미 다른 파일이 열려있는 경우 WaitForExit 가 먹히지 않음
그래서 별도 Process 로 Excel 을 실행시킴
void ExecuExcelAsAnotherProcess()
{
string excelProcessPath = "";
string fileName = @"C:\Users\Administrator\Downloads\Test.xlsx_";
try
{
this.Cursor = Cursors.WaitCursor;
excelProcessPath = GetExcelProcessPath();
string cmd = string.Format(""{0}" /x "{1}"", excelProcessPath, fileName);
System.Diagnostics.ProcessStartInfo psInfo = new System.Diagnostics.ProcessStartInfo(cmd);
psInfo.CreateNoWindow = false;
psInfo.UseShellExecute = false;
using (System.Diagnostics.Process ps = System.Diagnostics.Process.Start(psInfo))
{
ps.EnableRaisingEvents = true;
ps.WaitForExit();
}
}
finally
{
this.Cursor = Cursors.Default;
}
}
string GetExcelProcessPath()
{
dynamic app = null;
try
{
Type excelType = Type.GetTypeFromProgID("Excel.Application");
app = Activator.CreateInstance(excelType);
app.Visible = true;
app.DisplayAlerts = true;
return Path.Combine(app.Path, "excel.exe");
}
finally
{
if (app != null)
{
app.Quit();
}
NAR(app);
}
}
void NAR(object obj)
{
try
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
}
}
catch { }
finally
{
obj = null;
}
}
0 Comments