Public void writeexcel (Datagridview ds, string path) { try { SaveFileDialog saveFileDialog = new SaveFileDialog (); saveFileDialog.Filter = "execl files (*.xls) |*.xls"; savefiledialog.filterindex = 0; savefiledialog.restoredirectory = true; savefiledialog.createprompt = false; saveFileDialog.Title = "Export Excel file to"; saveFileDialog.FileName = Path; if (Savefiledialog.showdialog () == dialogresult.ok) { Stream myStream; Mystream = savefiledialog.openfile (); &nbsP; streamwriter sw = new streamwriter (myStream, Encoding.GetEncoding ("gb2312")); stringbuilder sb = new stringbuilder (); messagebox.show (ds. Rows.count+ "," +ds. ColumnCount); for (Int i = 0; i < ds. columncount; i++) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SB. Append (ds. Columns[i]. Headertext +&nBSP; " \ t "); } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SB. Append (Environment.NewLine);//Line wrapping after each line of data //Write Content for (int j = 0; j < ds. rows.count; j++) { for (int k = 0; k < ds. columncount; k++) &NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SB. Append (ds. ROWS[J]. CELLS[K]. Value.tostring () + "\ T"); } sb . Append (Environment.NewLine);//Line wrapping after each line of data } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SW. Write (sb.) ToString ()); &nbsP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SW. Flush (); &NBSP;&NBSP;&NBSP;SW. Close ();//Release Resources killspecialexcel (); messagebox.show ("The specified Excel file has been generated!"); } } catch (Exception ex) { messagebox.show (ex. Message); } }
StreamWriter (DataGridView) Export Excel