// 载入一个csv文件并解析 private static bool LoadCsv(string file, bool checkValid, out List <Dictionary <string, string> > records, out List <CsvField> fields, out string primaryKey) { return(ParseLines(FileMgr.ReadLines(file), checkValid, out records, out fields, out primaryKey)); }
/// <summary> /// 序列化csv文件操作. /// </summary> public static void Save(string filePath, bool checkValid, string dir) { CsvFile csv = new CsvFile(System.IO.Path.GetFileNameWithoutExtension(filePath)); string[] lines = FileMgr.ReadLines(filePath); if (lines.Length == 0) { NIDebug.Log("空文件 {0}", lines); return; } // 解析csv文件 CsvParser cp = new CsvParser(); LPCValue m; try { cp.Load(filePath, checkValid); if (cp.Fields.Count == 0 || cp.Records.Count == 0) { return; } m = ImportMgr.Read(cp); } catch (Exception e) { NIDebug.Log("读取csv错误 {0}\n{1}", filePath, e.ToString()); return; } // 主key csv.primaryKey = cp.PrimaryKey; // 列名字对应的索引 for (int i = 0; i < cp.Fields.Count; i++) { csv.columns.Add(cp.Fields[i].name, i); } // 每列值 csv.rows = new CsvRow[m.AsArray.Count]; for (int i = 0; i < m.AsArray.Count; i++) { LPCValue v = m.AsArray[i]; CsvRow row = new CsvRow(csv); for (int idx = 0; idx < cp.Fields.Count; idx++) { row.Add(idx, v.AsMapping[cp.Fields[idx].name]); } csv.AddRow(i, row); } // 序列化 MemoryStream ms = new MemoryStream(); CsvFileMgr.Serialize(ms, csv); // 写入数据 string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath); // 确保路径存在 Directory.CreateDirectory(dir); FileStream fs = new FileStream(dir + "/" + fileName + CSV_EXT, FileMode.Create, FileAccess.Write); fs.Write(ms.GetBuffer(), 0, (int)ms.Length); fs.Close(); }