Files
wg_cpso/ToolPathParser/CsvFileHelper.cs
2026-03-25 18:20:24 +08:00

72 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using System.Text;
using System;
using System.IO;
/*
* 测试代码由Luke添加并维护
*/
namespace ToolPathParser
{
public static class CsvFileHelper
{
// 将对象列表写入CSV文件
public static void WriteListToCsv<T>(List<T> dataList, string filePath)
{
if (dataList == null || dataList.Count == 0)
{
throw new ArgumentException("数据列表不能为空", nameof(dataList));
}
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("文件路径不能为空", nameof(filePath));
}
StringBuilder csvContent = new StringBuilder();
var properties = typeof(T).GetProperties();
// 第一步写入CSV表头使用对象的属性名作为列名
List<string> headerNames = new List<string>();
foreach (var prop in properties)
{
headerNames.Add(CsvFileHelper.EscapeCsvValue(prop.Name));
}
csvContent.AppendLine(string.Join(",", headerNames));
// 第二步:写入数据行
foreach (var item in dataList)
{
List<string> rowValues = new List<string>();
foreach (var prop in properties)
{
// 获取属性值并处理空值
object value = prop.GetValue(item) ?? string.Empty;
// 转义CSV特殊字符
rowValues.Add(CsvFileHelper.EscapeCsvValue(value.ToString()));
}
csvContent.AppendLine(string.Join(",", rowValues));
}
// 第三步将内容写入文件使用UTF-8编码避免中文乱码
File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);
}
// 转义CSV格式的特殊字符逗号、引号、换行符
private static string EscapeCsvValue(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
if (value.Contains(",") || value.Contains("\"") || value.Contains("\n") || value.Contains("\r"))
{
return $"\"{value.Replace("\"", "\"\"")}\"";
}
return value;
}
}
}