C#中关于CSV文件的写入和读取

时间:2021-10-19 21:22:16


        /// <summary>
        /// 保存CSV文档
        /// </summary>
        /// <param>地址</param>
        /// <param>內容</param>
        /// <param>是否覆蓋保存,false覆盖</param>
        public static void WriteCSV(string filePathName, List<string[]> rows, bool append)         
        { 
            StreamWriter fileWriter=new StreamWriter(filePathName,append,Encoding.Default);
            foreach (string[] cells in rows)             
            {
                StringBuilder buffer = new StringBuilder();
                for (int i = 0; i < cells.Length; ++i)
                {
                    string str = cells[i].Replace("\"", "").Trim();
                    if (str == null)
                        str = "";
                    if(str.IndexOf(",")>-1){
                        str = "\""+str+"\"";
                    }
                    buffer.Append(str);
                    if (i != cells.Length - 1)
                        buffer.Append(quotechar);
                }
                fileWriter.WriteLine(buffer.ToString());             
            }
            fileWriter.Flush();             
            fileWriter.Close();
        }

---------------------------------------------------------------------------------------------------

/// <summary>
        /// 讀取文檔文件
        /// </summary>
        /// <param>地址</param>
        /// <returns>返回內容</returns>
        public static List<string[]> ReadCSV(string filePathName)
        {
            StreamReader fileReader = new StreamReader(filePathName, Encoding.Default);
            string rowStr = fileReader.ReadLine();
            // "a,1",b,c     // "\"a,1\",\"b,1,2\",\"c,cc\",ddd"
            List<string[]> rowList = new List<string[]>();
            while (rowStr != null) {
                List<string> cellVals = getStrCellVal(rowStr);
                string[] cells = new string[cellVals.Count];
                for (int i = 0; i < cellVals.Count; i++) {
                    cells[i] = cellVals[i];
                }
                rowList.Add(cells);
                rowStr = fileReader.ReadLine();
            }
            fileReader.Close();
            return rowList;
        }