| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace YangjieTester
- {
- public static class ExportData
- {
- public static void ExportDataGridViewToCsv(DataGridView dgv, string filePath)
- {
- var sb = new StringBuilder();
- // 1. 写入列标题(跳过 RowHeaders)
- var headers = new List<string>();
- foreach (DataGridViewColumn col in dgv.Columns)
- {
- if (col.Visible) // 只导出可见列
- //headers.Add($"\"{col.HeaderText.Replace("\"", "\"\"")}\"");
- headers.Add(EscapeCsvField(col.HeaderText));
- }
- sb.AppendLine(string.Join(",", headers));
- // 2. 写入每一行数据
- foreach (DataGridViewRow row in dgv.Rows)
- {
- if (row.IsNewRow) continue; // 跳过新增行
- var cells = new List<string>();
- foreach (DataGridViewCell cell in row.Cells)
- {
- if (!dgv.Columns[cell.ColumnIndex].Visible) continue;
- string value;
- if (cell.Value == null || cell.Value == DBNull.Value)
- {
- value = "";
- }
- else if (cell.Value is DateTime dt)
- {
- // ✅ 关键修复:显式格式化为包含秒(甚至毫秒)
- // 根据你的需求选择格式:
- //value = "'" + dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
- value = "\u200B" + dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
-
- }
- else
- {
- value = cell.Value.ToString();
- }
- cells.Add(EscapeCsvField(value));
- }
- sb.AppendLine(string.Join(",", cells));
- }
- // 3. 写入文件
- File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
- }
- // 辅助方法:正确转义 CSV 字段
- private static string EscapeCsvField(string value)
- {
- if (string.IsNullOrEmpty(value))
- return "";
- // 如果是我们手动加了单引号前缀(表示文本),则不加双引号
- if (value.StartsWith("'"))
- return value; // 直接返回,如:'2025-11-12 10:47:17.591
- // 否则,按标准 CSV 规则:含逗号、换行、引号的字段用双引号包裹
- if (value.Contains(",") || value.Contains("\n") || value.Contains("\""))
- return "\"" + value.Replace("\"", "\"\"") + "\"";
- return value;
- }
- public static void ExportDataToTxt(string txt,string filePath)
- {
- File.WriteAllText(filePath, txt, Encoding.UTF8);
- }
- }
- }
|