private void DataGridViewToExcel(DataGridView dataGridView1) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存为Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = dlg.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { //写入列标题 for (int i = 0; i < dataGridView1.ColumnCount; i++) { if (i > 0) { columnTitle += " "; } columnTitle += dataGridView1.Columns[i].HeaderText; } sw.WriteLine(columnTitle); //写入列内容 for (int j = 0; j < dataGridView1.Rows.Count; j++) { string columnValue = ""; for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (k > 0) { columnValue += " "; } if (dataGridView1.Rows[j].Cells[k].Value == null) columnValue += ""; else columnValue += dataGridView1.Rows[j].Cells[k].Value.ToString().Trim(); } sw.WriteLine(columnValue); } sw.Close(); myStream.Close(); MessageBox.Show("导出成功!"); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } }