视频课:https://edu.csdn.net/course/detail/27107
publicvoid outExcel(DataGridView gridView) { if (gridView.Rows.Count== 0) { MessageBox.Show("没有数据可供导出!","提示", MessageBoxButtons.OK,MessageBoxIcon.Information); return; } else { SaveFileDialog saveFileDialog= new SaveFileDialog(); saveFileDialog.Filter= "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex= 0; saveFileDialog.RestoreDirectory= true; saveFileDialog.CreatePrompt= true; saveFileDialog.Title= "保存为Excel文件"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName.IndexOf(":")< 0) return; //被点了"取消" Stream myStream; myStream= saveFileDialog.OpenFile(); StreamWriter sw= new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle= ""; try { //写入列标题 for (inti = 0; i < this.dataGridView1.ColumnCount; i++) { if (i> 0) { columnTitle+= "\t"; } columnTitle+= this.dataGridView1.Columns[i].HeaderText; } sw.WriteLine(columnTitle); //写入列内容 for (intj = 0; j { string columnValue= ""; for (intk = 0; k < this.dataGridView1.Columns.Count; k++) { if (k> 0) { columnValue+= "\t"; } if (this.dataGridView1.Rows[j].Cells[k].Value== null) columnValue+= ""; else columnValue+= this.dataGridView1.Rows[j].Cells[k].Value.ToString().Trim(); } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); } catch (Exceptione) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } }