Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refreshing excel file which gets its data from sql server with c#

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");
    }
like image 292
Arif YILMAZ Avatar asked Dec 20 '25 06:12

Arif YILMAZ


1 Answers

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.

like image 176
T J Avatar answered Dec 22 '25 19:12

T J