WinForm--DataGridView导出数据到CSV文件


 1 /// <summary>
 2         /// 导出数据到CSV文件  3         /// </summary>
 4         /// <param name="fileName"></param>
 5         /// <param name="table"></param>
 6         private void ExportDataToCSV(string fileName, DataTable table)  7  {  8             if (table == null || table.Rows.Count == 0)  9  { 10                 return; 11  } 12 
13             SaveFileDialog saveDlg = new SaveFileDialog(); 14             saveDlg.Filter = "CSV文件(*.csv)|*.csv"; 15             saveDlg.FileName = fileName + DateTime.Now.ToString("yyyyMMdd"); 16 
17             if (saveDlg.ShowDialog() == DialogResult.OK) 18  { 19                 FileStream fs = new FileStream(saveDlg.FileName, FileMode.Create); 20                 StreamWriter write = new StreamWriter(fs, Encoding.Default); 21                 try
22  { 23                     //标题行
24                     string userCode = table.Columns["UserCode"].ColumnName = "用户名称"; 25                     string userKey = table.Columns["UserKey"].ColumnName = "用户编码"; 26                     string isRegist = table.Columns["IsRegist"].ColumnName = "是否注册"; 27                     string serial = table.Columns["Serial"].ColumnName = "序列号"; 28                     string isEnable = table.Columns["IsEnable"].ColumnName = "是否启用"; 29                     write.Write(userCode + ","); 30                     write.Write(userKey + ","); 31                     write.Write(isRegist + ","); 32                     write.Write(serial + ","); 33                     write.Write(isEnable + ","); 34 
35  write.WriteLine(); 36 
37                     //明细行
38                     for (int row = 0; row < table.Rows.Count; row++) 39  { 40                         string Tem = ""; 41                         for (int column = 2; column <= table.Columns.Count - 1; column++) 42  { 43                             if (table.Rows[row][column] != DBNull.Value) 44  { 45                                 string TemString = table.Rows[row][column].ToString().Trim(); 46                                 Tem += TemString + "\t"; 47                                 Tem += ","; 48  } 49                             else
50  { 51                                 string TemString = ""; 52                                 Tem += TemString; 53                                 Tem += ","; 54  } 55  } 56  write.WriteLine(Tem); 57  } 58  write.Flush(); 59  write.Close(); 60                     MessageBox.Show("导出成功:" + saveDlg.FileName.ToString().Trim()); 61  } 62                 catch (Exception ex) 63  { 64  MessageBox.Show(ex.ToString()); 65  write.Close(); 66  } 67  } 68         }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM