I have been searching a tutorial for c# to refresh an excel file without opening the excel and clicking the refresh button. I found the solution and it is very easy. I wanted to share
private void ExcelRefresh(string Filename)
{
try
{
object NullValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
//excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook Workbook = excelApp.Workbooks.Open(
Filename, NullValue, NullValue, NullValue, NullValue,
NullValue, NullValue, NullValue, NullValue, NullValue,
NullValue, NullValue, NullValue, NullValue, NullValue);
Workbook.RefreshAll();
System.Threading.Thread.Sleep(20000);
Workbook.Save();
Workbook.Close(false, Filename, null);
excelApp.Quit();
Workbook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
ExcelRefresh(@"D:\test.xlsx");
}
why not just tell excel to do the refresh when the file is opened? Data->Connections and then check "Refresh data when opening the file"
much simpler solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With