88 lines
2.1 KiB
C#
88 lines
2.1 KiB
C#
using System.Globalization;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
// 寫 CSV 的小工具 : 先寫到 .tmp,回合完成才 Commit 改成正式檔名,沒完成就 Discard 刪掉
|
|
// 數字一律用 InvariantCulture (小數點是 .,不受電腦語言設定影響)
|
|
public class CsvWriter
|
|
{
|
|
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
|
|
|
private readonly string finalPath;
|
|
private readonly string tmpPath;
|
|
private readonly StreamWriter writer;
|
|
private readonly StringBuilder row = new StringBuilder(512);
|
|
|
|
public int Rows { get; private set; }
|
|
|
|
public CsvWriter(string path, string header)
|
|
{
|
|
finalPath = path;
|
|
tmpPath = path + ".tmp";
|
|
writer = new StreamWriter(tmpPath, false, new UTF8Encoding(false), 1 << 16);
|
|
writer.WriteLine(header);
|
|
}
|
|
|
|
public CsvWriter Add(double value, string format = "0.######")
|
|
{
|
|
Separator();
|
|
row.Append(value.ToString(format, Inv));
|
|
return this;
|
|
}
|
|
|
|
public CsvWriter Add(float value) => Add((double)value);
|
|
|
|
public CsvWriter Add(int value)
|
|
{
|
|
Separator();
|
|
row.Append(value.ToString(Inv));
|
|
return this;
|
|
}
|
|
|
|
public CsvWriter Add(bool value)
|
|
{
|
|
Separator();
|
|
row.Append(value ? '1' : '0');
|
|
return this;
|
|
}
|
|
|
|
public CsvWriter Add(string value)
|
|
{
|
|
Separator();
|
|
if (!string.IsNullOrEmpty(value)) row.Append(value.Replace(',', ' '));
|
|
return this;
|
|
}
|
|
|
|
// 空欄位 (這個事件沒有這項資料)
|
|
public CsvWriter Empty()
|
|
{
|
|
Separator();
|
|
return this;
|
|
}
|
|
|
|
public void EndRow()
|
|
{
|
|
writer.WriteLine(row.ToString());
|
|
row.Clear();
|
|
Rows++;
|
|
}
|
|
|
|
public void Commit()
|
|
{
|
|
writer.Dispose();
|
|
if (File.Exists(finalPath)) File.Delete(finalPath);
|
|
File.Move(tmpPath, finalPath);
|
|
}
|
|
|
|
public void Discard()
|
|
{
|
|
writer.Dispose();
|
|
if (File.Exists(tmpPath)) File.Delete(tmpPath);
|
|
}
|
|
|
|
void Separator()
|
|
{
|
|
if (row.Length > 0) row.Append(',');
|
|
}
|
|
}
|