72 lines
2.4 KiB
C#
72 lines
2.4 KiB
C#
|
|
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;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|