ExportData.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. namespace YangjieTester
  10. {
  11. public static class ExportData
  12. {
  13. public static void ExportDataGridViewToCsv(DataGridView dgv, string filePath)
  14. {
  15. var sb = new StringBuilder();
  16. // 1. 写入列标题(跳过 RowHeaders)
  17. var headers = new List<string>();
  18. foreach (DataGridViewColumn col in dgv.Columns)
  19. {
  20. if (col.Visible) // 只导出可见列
  21. //headers.Add($"\"{col.HeaderText.Replace("\"", "\"\"")}\"");
  22. headers.Add(EscapeCsvField(col.HeaderText));
  23. }
  24. sb.AppendLine(string.Join(",", headers));
  25. // 2. 写入每一行数据
  26. foreach (DataGridViewRow row in dgv.Rows)
  27. {
  28. if (row.IsNewRow) continue; // 跳过新增行
  29. var cells = new List<string>();
  30. foreach (DataGridViewCell cell in row.Cells)
  31. {
  32. if (!dgv.Columns[cell.ColumnIndex].Visible) continue;
  33. string value;
  34. if (cell.Value == null || cell.Value == DBNull.Value)
  35. {
  36. value = "";
  37. }
  38. else if (cell.Value is DateTime dt)
  39. {
  40. // ✅ 关键修复:显式格式化为包含秒(甚至毫秒)
  41. // 根据你的需求选择格式:
  42. //value = "'" + dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
  43. value = "\u200B" + dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
  44. }
  45. else
  46. {
  47. value = cell.Value.ToString();
  48. }
  49. cells.Add(EscapeCsvField(value));
  50. }
  51. sb.AppendLine(string.Join(",", cells));
  52. }
  53. // 3. 写入文件
  54. File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
  55. }
  56. // 辅助方法:正确转义 CSV 字段
  57. private static string EscapeCsvField(string value)
  58. {
  59. if (string.IsNullOrEmpty(value))
  60. return "";
  61. // 如果是我们手动加了单引号前缀(表示文本),则不加双引号
  62. if (value.StartsWith("'"))
  63. return value; // 直接返回,如:'2025-11-12 10:47:17.591
  64. // 否则,按标准 CSV 规则:含逗号、换行、引号的字段用双引号包裹
  65. if (value.Contains(",") || value.Contains("\n") || value.Contains("\""))
  66. return "\"" + value.Replace("\"", "\"\"") + "\"";
  67. return value;
  68. }
  69. public static void ExportDataToTxt(string txt,string filePath)
  70. {
  71. File.WriteAllText(filePath, txt, Encoding.UTF8);
  72. }
  73. }
  74. }