老問題一枚。使用Excel開啟CSV檔案,會l將純數字組成的字串視為數字型別處理,導致"000123"之類的左補零數字編碼變成"123"(如下圖所示),對必須補零到固定長度的編碼欄位來說,莫名被截掉部分內容,常會造成困擾。所幸,透過簡單的CSV花式技巧,在CSV中寫成="000123",就可強迫Excel將其視為文字處理,避免前方的零被截除。
遇到一個棘手情境: 某CSV檔需符合其他系統上傳規格,不能輸出成="000123"的形式,偏偏使用者又常需用Excel開啟CSV檔編輯後另存CSV再上傳。要符合上傳規格CSV內容就必須直接輸出000123,當使用者以Excel開啟時會有左補零被截除的困擾;若輸出成="000123",若使用者拿來直接上傳其他系統則會出錯。
最後我決定寫一個.NET Windows Form小工具,讓使用者放在桌面上,當需要開啟這類含左補零數字CSV時,不要直接點選CSV開Excel,而是透過小工具選取檔案,小工具會讀取CSV內容,將所有欄位內容重新包裝成="…"格式,全部當成字串,再另存成*.fixed.csv(修正版),最後啟動Excel開啟修正後的CSV,避開左補零被截除的問題。
using System.Windows.Forms;
using System.Diagnostics;
static Encoding big5Enc = Encoding.GetEncoding(950);
public static bool IsBig5Encoding(string file)
if (!File.Exists(file)) return false;
byte[] data = File.ReadAllBytes(file);
big5Enc.GetByteCount(big5Enc.GetString(data));
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.csv|*.csv";
if (ofd.ShowDialog() == DialogResult.OK)
string fn = ofd.FileName;
IsBig5Encoding(fn) ? big5Enc : Encoding.UTF8;
using (StreamReader sr = new StreamReader(fn, enc))
StringBuilder sb = new StringBuilder();
while ((line = sr.ReadLine()) != null)
string[] p = line.Split(',');
sb.AppendLine(string.Join(",",
p.Select(o => string.Format("=\"{0}\"", o)).ToArray()
//調整結果另存為同目錄下*.fixed.csv檔
string fixedFile = Path.Combine(
Path.GetDirectoryName(fn),
Path.GetFileNameWithoutExtension(fn) + ".fixed.csv");
File.WriteAllText(fixedFile, sb.ToString(), enc);
Process proc = new Process();
proc.StartInfo = new ProcessStartInfo(fixedFile);
MessageBox.Show("Error: " + ex.Message);