How to export data to excel
// How to export data to excel Public Bool Exportdatagridviewexcel (datagridview gridview, Bool Isshowexcel ){ If (Gridview. Rows. Count = 0 ){ Return False ;} // Create an Excel Object Excel. Application Excel = New Excel. Application (); excel. application. workbooks. Add ( True ); Excel. Visible = Isshowexcel; // Generate field name For ( Int I = 0 ; I <gridview. Columns. Count; I ++ ) {Excel. cells [ 1 , I + 1 ] = Gridview. Columns [I]. headertext ;} // Fill data For ( Int I = 0 ; I <gridview. Rows. Count- 1 ; I ++ ){ For ( Int J = 0 ; J <gridview. Columns. Count; j ++){ If (Gridview [J, I]. valuetype = Typeof ( String ) {Excel. cells [I + 2 , J + 1 ] = "" + Gridview [J, I]. value. tostring ();} Else {Excel. cells [I +2 , J + 1 ] = Gridview [J, I]. value. tostring ();}}} Return True ;}
Export to word Method
// Export to word Method Public Bool Exportdatagridviewword (datagridview gridview, Bool Isshowexcel ){ If (Gridview. Rows. Count = 0 ){ Return False ;} Word. Document mydoc = New Word. Document (); Word. Table mytable; Word. Selection mysel; object myobj; // Create a word object Word. Application word = New Word. Application (); myobj = System. reflection. Missing. value; mydoc = Word. Documents. Add ( Ref Myobj, Ref Myobj, Ref Myobj, Ref Myobj); Word. Visible = Isshowexcel; mydoc. Select (); Mysel = Word. selection; // Generate a Word Table File Mytable = mydoc. Tables. Add (mysel. Range, This . Maid, This . Datagridview1.columncount, Ref Myobj, Ref Myobj ); // Set column width Mytable. Columns. setwidth ( 30 , Word. wdrulerstyle. wdadjustnone ); // Output Column Title data For (Int I = 0 ; I < This . Datagridview1.columncount; I ++ ) {Mytable. Cell ( 1 , I + 1 ). Range. insertafter ( This . Maid [I]. headertext );} // Records in the output control For ( Int I = 0 ; I < This . Datagridview1.rowcount- 1 ; I ++ ){ For ( Int J = 0 ; J < This . Datagridview1.columncount; j ++ ) {Mytable. Cell (I + 2 , J + 1 ). Range. insertafter ( This . Datagridview1 [J, I]. value. tostring ());}} Return True ;}