void RefreshWorkbookTwo(string SourcePath, string SourceFilename, string ReportName, Guid ExecutionID )
{
try
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelApp.DisplayAlerts = false;
// if Visible is set to false we get an exception for some reason
excelApp.Visible = false;
Workbook excelWorkbook = excelApp.Workbooks.Open(
SourcePath + SourceFilename,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value);
// pivot tables are normally refreshed in a background thread
// setting this to false means that we can save synchronously
Console.WriteLine("Iterating through the Query Tables...");
foreach (Worksheet ws in excelWorkbook.Worksheets)
{
foreach (QueryTable qt in ws.QueryTables )
{
qt.BackgroundQuery = false;
}
}
foreach (PivotCache cache in excelWorkbook.PivotCaches())
{
cache.BackgroundQuery = false;
}
Console.WriteLine("Refreshing...");
excelWorkbook.RefreshAll();
var refreshedWorkBookPath = Path.Combine(Path.GetDirectoryName(SourcePath + SourceFilename), Path.ChangeExtension(Path.GetFileName(Path.GetTempFileName()), "xls"));
Console.WriteLine("Saving...");
excelWorkbook.Save();
// ensure all excel objects are closed and references are released
// if this is not done an instance of excel will stay in the running processes
excelWorkbook.Close(false, SourcePath + SourceFilename, null);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
excelWorkbook = null;
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;
}
catch (Exception e)
{
///Sending message to me and Marie Coleman on failure
String failureMessage = "The " + ReportName + " failed " + DateTime.Now.ToString() + " with the following error:\n\nSource: " + e.Source.ToString() + "\n\nMessage: " + e.Message.ToString();
SendMessage(ReportName + " Application Failure", failureMessage);
///Writing to error file
ProcessLog(ExecutionID, "ReportRunner application error", "ERROR", DateTime.Now, "ReportRunner", "ReportRunner Application", "Application Error", null, null, failureMessage);
///Killing the Excel process if it's active
KillProcesses("EXCEL");
}
finally
{
KillProcesses("EXCEL");
}