private void datatabletocsv (DataTable table, string file) {string title = ""; FileStream fs = new FileStream (file, FileMode.OpenOrCreate); FileStream FS1 = File.Open (File, FileMode.Open, FileAccess.Read); StreamWriter SW = new StreamWriter (new BufferedStream (FS), System.Text.Encoding.Default); for (int i = 0; i < table. Columns.count; i++) {title + = table. Columns[i]. ColumnName + "\ T"; Field: Automatically jumps to the next cell} title = title. Substring (0, title. Length-1) + "\ n"; Sw. Write (title); foreach (DataRow row in table. Rows) {String line = ""; for (int i = 0; i < table. Columns.count; i++) {line + = Row[i]. ToString (). Trim () + "\ T"; Content: Automatically jumps to the next cell} line = line. Substring (0, line. Length-1) + "\ n"; Sw. Write (line); } SW. CLose (); Fs. Close (); MessageBox.Show ("Data export succeeded!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information); } public void M_mthexport () {//datatabletocsv (); SaveFileDialog dlg = new SaveFileDialog (); Dlg. Filter = "execl files (*.xls) |*.xls"; Dlg. Filter = "Excel 2003|*.xls| Excel 2007|*.xlsx "; Dlg. Checkfileexists = false; Dlg. Checkpathexists = false; Dlg. FilterIndex = 0; Dlg. Restoredirectory = true; Dlg. Createprompt = false; Dlg. Title = "Save as Excel file"; if (dlg. ShowDialog () = = DialogResult.OK) {string ss = Dlg. FileName; Datatabletocsv (Dtsource,dlg. FileName); }//Datagridviewtoexcel (m_objviewer.dgvreportlist); } public void Datagridviewtoexcel (DataGridView dgv) {SaveFileDialog dlg = new SaveFileDialog (); Dlg. Filter = "Execl fIles (*.xls) |*.xls "; Dlg. Filter = "Excel 2003|*.xls| Excel 2007|*.xlsx "; Dlg. Checkfileexists = false; Dlg. Checkpathexists = false; Dlg. FilterIndex = 0; Dlg. Restoredirectory = true; Dlg. Createprompt = false; Dlg. Title = "Save as Excel file"; if (dlg. ShowDialog () = = DialogResult.OK) {Stream mystream; MyStream = dlg. OpenFile (); StreamWriter SW = new StreamWriter (MyStream, System.Text.Encoding.GetEncoding (-0)); String columntitle = ""; try {//Write column header for (int i = 0; i < DGV. ColumnCount; i++) {if (i > 0) {columnt Itle + = "\ T"; } Columntitle + = DGV. Columns[i]. HeaderText; } SW. WriteLine (ColumntiTLE); Writes the column contents for (int j = 0; J < DGV. Rows.Count; J + +) {string columnvalue = ""; for (int k = 0; k < DGV. Columns.count; k++) {if (k > 0) { Columnvalue + = "\ T"; } if (DGV. ROWS[J]. CELLS[K]. Value = = null) Columnvalue + = ""; else Columnvalue + = DGV. ROWS[J]. CELLS[K]. Value.tostring (). Trim (); } SW. WriteLine (Columnvalue); } SW. Close (); Mystream.close (); MessageBox.Show ("Data export succeeded!", "hint", MessageBoxButtons.OK); } catch (Exception e) {MessageBox.Show (e.tOstring ()); } finally {SW. Close (); Mystream.close (); } } }
Datatable,datagridview Convert to Xls method (GO)