このCSVエクスポートクラスにリストを渡す必要があります
-
27-10-2019 - |
質問
このCSVエクスポートクラスをオンラインで見つけたので、別のクラスから自分のリストを渡したいと思います。私のリストはすでに準備されており、3つの列が含まれています
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using System.IO;
using System.Reflection;
public class CsvExport<T> where T : class
{
public List<T> Objects;
public CsvExport(List<T> objects)
{
Objects = objects;
}
public string Export()
{
return Export(true);
}
public string Export(bool includeHeaderLine)
{
StringBuilder sb = new StringBuilder();
//Get properties using reflection.
IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
if (includeHeaderLine)
{
//add header line.
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(propertyInfo.Name).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
//add value for each property.
foreach (T obj in Objects)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
return sb.ToString();
}
//export to a file.
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
//export as binary data.
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
//get the csv value for field.
private string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
}
解決
クラスの使用を助けたいなら、私はあなたがこのようなことをする必要があると言うでしょう。
データのクラスを作成します。
public class MyData
{
public string Column1Data {get;set;}
public string Column2Data {get;set;}
public string Column3Data {get;set;}
}
このようなcsvexportクラスへのタイプmydataのリストをパス...
List<MyData> list = new List<MyData>();
//populate the list here
CsvExport<MyData> export = new CsvExport<MyData>();
export.ExportToFile(@"C:\MyExportFile.txt");
今、あなたは次のような出力ファイルを持っているはずです...
Column1Data,Column2Data,Column3Data
r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
r3c1,r1c2,r3c3
別の入力クラスを使用するには、MyDataの参照を切り替えるだけです。
他のヒント
サンプルクラスで輸出業者を使用するサンプルは次のとおりです
class Sample
{
public string Field1 {get;set;}
public int Field2 {get;set;}
}
List<Sample> source = new List<Sample>()
// fill list
CsvExport<Sample> export = new CsvExport<Sample>(source);
export.ExportToFile("yourFile.csv");
基本的に作成されます CsvExport<YourClass>
既存のオブジェクトのパスリスト
所属していません StackOverflow