You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.0 KiB
62 lines
2.0 KiB
|
4 weeks ago
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using System.IO;
|
||
|
|
using System.Reflection;
|
||
|
|
using System.Text;
|
||
|
|
using System.Windows;
|
||
|
|
|
||
|
|
namespace leak_test_project.Utils
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// 데이터를 CSV 파일로 내보내는 유틸리티
|
||
|
|
/// </summary>
|
||
|
|
public static class CsvExporter
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// 컬렉션 데이터를 CSV 파일로 저장함
|
||
|
|
/// </summary>
|
||
|
|
/// <typeparam name="T">데이터 모델 클래스</typeparam>
|
||
|
|
/// <param name="items">내보낼 데이터 목록</param>
|
||
|
|
/// <param name="filePath">저장할 파일 경로</param>
|
||
|
|
public static bool ExportToCsv<T>(IEnumerable<T> items, string filePath)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var sb = new StringBuilder();
|
||
|
|
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
||
|
|
|
||
|
|
// Header
|
||
|
|
foreach (var prop in props)
|
||
|
|
{
|
||
|
|
sb.Append(prop.Name).Append(",");
|
||
|
|
}
|
||
|
|
sb.AppendLine();
|
||
|
|
|
||
|
|
// Body
|
||
|
|
foreach (var item in items)
|
||
|
|
{
|
||
|
|
foreach (var prop in props)
|
||
|
|
{
|
||
|
|
var val = prop.GetValue(item, null);
|
||
|
|
var str = val?.ToString() ?? "";
|
||
|
|
if (str.Contains(",") || str.Contains("\"") || str.Contains("\n"))
|
||
|
|
sb.Append($"\"{str.Replace("\"", "\"\"")}\"");
|
||
|
|
else
|
||
|
|
sb.Append(str);
|
||
|
|
sb.Append(",");
|
||
|
|
}
|
||
|
|
sb.AppendLine();
|
||
|
|
}
|
||
|
|
|
||
|
|
File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
MessageBox.Show($"CSV 저장 실패: {ex.Message}");
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|