c# - How to export data from DataGridView without using FileDialog? -


i have button called export data. when click on button data should store default in file "abc.xls".

i able store data when try store values 2nd time getting comexception.

can suggest me on this?

i not want have filedialog. since using default file , everytime change override file. in advance.

xlapp = new microsoft.office.interop.excel.application(); xlworkbook = xlapp.workbooks.add(misvalue); xlworksheet =          (microsoft.office.interop.excel.worksheet)xlworkbook.worksheets.get_item(1); int = 0; int j = 0; (i = 0; <= datagridview1.rowcount - 1; i++)  {     (j = 0; j <= datagridview1.columncount - 1; j++)     {       datagridviewcell cell = datagridview1[j, i];       xlworksheet.cells[i + 1, j + 1] = cell.value;     }  }  xlworkbook.saveas(@"c:\abc.xls",                 microsoft.office.interop.excel.xlfileformat.xlworkbooknormal, misvalue,                 misvalue, misvalue, misvalue,                  microsoft.office.interop.excel.xlsaveasaccessmode.xlexclusive,                   misvalue, misvalue, misvalue, misvalue, misvalue);                  // comexception thrown here   xlworkbook.close(true, misvalue, misvalue);  xlapp.quit();   releaseobject(xlworksheet);  releaseobject(xlworkbook);  releaseobject(xlapp); 

saying .xls , comexception, suspect mean saving via excel com automation. set displayalerts = false , use saveas method. ie:

void main() {     var f = new form {text = "excel saveas sample"};     var b = new system.windows.forms.button {text="save xls", autosize = true};     var dgv = new datagridview {top=60};      var tbl = new system.data.datatable();     new sqldataadapter(       "select customerid, companyname, contactname customers",        @"server=.\sqlexpress;database=northwind;trusted_connection=yes")       .fill( tbl );      dgv.datasource = tbl;      f.controls.add( b );     f.controls.add( dgv );      b.click += (sender, args) => {       var xl = new microsoft.office.interop.excel.application();       var wb = xl.workbooks.add();       var sheet = (worksheet)wb.activesheet;        (int = 0; < dgv.columns.count; i++)       {         ((range)sheet.cells[1,i+1]).value = dgv.columns[i].headertext;       }        (int = 0; < tbl.rows.count; i++)       {         (int j = 0; j < tbl.columns.count; j++)         {           ((range)sheet.cells[i+2,j+1]).value = dgv.rows[i].cells[j].value.tostring();                  }       }       xl.displayalerts = false;       wb.saveas(@"d:\temp\abc.xls");       xl.quit();       messagebox.show("saved");     };      f.show(); } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -