using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack;
using Newtonsoft.Json;
using System.Dynamic;
namespace CsvTest
{
class Program
{
publicclass Entity
{
publicint Num { get; set; }
public DateTime Date { get; set; }
publicstring Text { get; set; }
publicbool Flag { get; set; }
public Entity(int num, DateTime date, string text, bool flag)
{
Num = num;
Date = date;
Text = text;
Flag = flag;
}
}
static Entity[] TestData = new Entity[]
{
new Entity(1, new DateTime(2012,12,21), "Normal", true),
new Entity(16, new DateTime(2012,12,21), "Taipei, Taiwan", true),
new Entity(32, new DateTime(2012,12,21), $@"""雙引號""跟,都來一下
換行當然不可少
", false)
};
staticvoid Main(string[] args)
{
//Test1();
//Test2();
Test3();
}
//物件陣列轉成CSV
staticvoid Test1()
{
File.WriteAllText("E:\\CSVLab\\Test1.csv",
CsvSerializer.SerializeToCsv<Entity>(TestData),
//指定new UTF8Encoding(true)產生包含BOM標記的UTF8檔案
//不然Excel直接開啟會有亂碼
new UTF8Encoding(true));
}
staticvoid Test2()
{
var csv = File.ReadAllText("E:\\CSVLab\\Test1.csv");
//記得using ServiceStack啟用擴充方法
var data = csv.FromCsv<List<Entity>>();
Console.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented));
Console.Read();
}
staticvoid Test3()
{
var csv = File.ReadAllText("E:\\CSVLab\\Test1.csv");
string[] propNames = null;
List<string[]> rows = new List<string[]>();
foreach (var line in CsvReader.ParseLines(csv))
{
string[] strArray = CsvReader.ParseFields(line).ToArray();
if (propNames == null)
propNames = strArray;
else
rows.Add(strArray);
}
Console.WriteLine($"PropNames={string.Join(",", propNames)}");
for (int r = 0; r < rows.Count; r++)
{
var cells = rows[r];
for (int c = 0; c < cells.Length; c++)
{
Console.WriteLine($"[{r},{c}]={cells[c]}");
}
}
Console.Read();
}
}
}