1 private void DataTableToExcel( DataTable table , string file ) 2 { 3 string title = ""; 4 5 using ( FileStream fs = new FileStream(file,FileMode.OpenOrCreate)) 6 { 7 using ( BufferedStream bs = new BufferedStream( fs ) ) 8 { 9 using ( StreamWriter sw = new StreamWriter(bs,Encoding.Default) ) 10 { 11 for ( int i = 0 ; i < table.Columns.Count ; i++ ) 12 { 13 title += table.Columns[ i ].ColumnName + "\t"; 14 } 15 //形成表格第一行的文本内容(每个字段的名称) 16 title = title.Substring( 0 , title.Length - 1 ) + "\n"; 17 sw.WriteLine( title ); 18 19 foreach ( DataRow row in table.Rows ) 20 { 21 string line = ""; 22 for ( int i = 0 ; i < table.Columns.Count ; i++ ) 23 { 24 line += row[ i ].ToString( ) + "\t"; 25 } 26 line += "\n"; 27 sw.WriteLine( line ); 28 } 29 sw.Close( ); 30 fs.Close( ); 31 } 32 } 33 } 34 }
1 //导出到Excel 2 private void button1_Click( object sender , EventArgs e ) 3 { 4 string filePath = @"c:\employee.xls"; 5 string sql = "select * from employee"; 6 DataTable dt = DBHelper.Query( sql , null , false ); 7 this.DataTableToExcel( dt , filePath ); 8 MessageBox.Show( "导出成功!" ); 9 }
浙公网安备 33010602011771号