C#中导出dataGridView数据为Excel

avatar
作者
猴君
阅读量:0

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);                  }              }          }      } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!