您的位置:首页 > 健康 > 养生 > C#中导出dataGridView数据为Excel

C#中导出dataGridView数据为Excel

2025/1/9 14:59:43 来源:https://blog.csdn.net/zzx2016zzx/article/details/140727103  浏览:    关键词:C#中导出dataGridView数据为Excel

C#中导出dataGridView数据为Excel

#region 导出Excel功能函数
/// <summary>
///  dataGridView 导出Excel功能函数
/// </summary>
/// <param name="dataView">dataGridView数据表</param>
/// <param name="filePath">路径</param>
private void ExportDataToExcel(DataGridView dataView, string filePath)
{try{using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8)){// 写入表头for (int i = 0; i < dataView.Columns.Count; i++){writer.Write(dataView.Columns[i].HeaderText);if (i < dataView.Columns.Count - 1){writer.Write(",");}}writer.WriteLine();// 写入数据foreach (DataGridViewRow row in dataView.Rows){if (!row.IsNewRow) // 忽略新行{for (int i = 0; i < dataView.Columns.Count; i++){writer.Write(row.Cells[i].Value?.ToString());if (i < dataView.Columns.Count - 1){writer.Write(",");}}writer.WriteLine();}}}MessageBox.Show("Data exported successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);}catch (Exception ex){MessageBox.Show("Error exporting data: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}
}#endregion

按键

     private void menuExportFile_Click(object sender, EventArgs e){using (SaveFileDialog saveFileDialog = new SaveFileDialog()){saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|CSV files (*.csv)|*.csv";saveFileDialog.Title = "Save as";saveFileDialog.FileName = $"{DateTime.Now:yyyyMMddHHmmss}"; // 默认文件名,以当前时间命名if (saveFileDialog.ShowDialog() == DialogResult.OK){string filePath = saveFileDialog.FileName;string fileExtension = Path.GetExtension(filePath).ToLower();if (fileExtension == ".csv"){ExportDataToExcel(dataView,filePath);}else if (fileExtension == ".xlsx"){ExportDataToExcel(dataView, filePath);}else{MessageBox.Show("Unsupported file format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}}}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com