CSV string handling

后端 未结 13 892
北荒
北荒 2020-12-28 16:44

Typical way of creating a CSV string (pseudocode):

  1. Create a CSV container object (like a StringBuilder in C#).
  2. Loop through the strings you want to ad
13条回答
  •  难免孤独
    2020-12-28 17:19

    I wrote a small class for this in case someone else finds it useful...

    public class clsCSVBuilder
    {
        protected int _CurrentIndex = -1;
        protected List _Headers = new List();
        protected List> _Records = new List>();
        protected const string SEPERATOR = ",";
    
        public clsCSVBuilder() { }
    
        public void CreateRow()
        {
            _Records.Add(new List());
            _CurrentIndex++;
        }
    
        protected string _EscapeString(string str)
        {
            return string.Format("\"{0}\"", str.Replace("\"", "\"\"")
                                                .Replace("\r\n", " ")
                                                .Replace("\n", " ")
                                                .Replace("\r", " "));
        }
    
        protected void _AddRawString(string item)
        {
            _Records[_CurrentIndex].Add(item);
        }
    
        public void AddHeader(string name)
        {
            _Headers.Add(_EscapeString(name));
        }
    
        public void AddRowItem(string item)
        {
            _AddRawString(_EscapeString(item));
        }
    
        public void AddRowItem(int item)
        {
            _AddRawString(item.ToString());
        }
    
        public void AddRowItem(double item)
        {
            _AddRawString(item.ToString());
        }
    
        public void AddRowItem(DateTime date)
        {
            AddRowItem(date.ToShortDateString());
        }
    
        public static string GenerateTempCSVPath()
        {
            return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().ToLower().Replace("-", "") + ".csv");
        }
    
        protected string _GenerateCSV()
        {
            StringBuilder sb = new StringBuilder();
    
            if (_Headers.Count > 0)
            {
                sb.AppendLine(string.Join(SEPERATOR, _Headers.ToArray()));
            }
    
            foreach (List row in _Records)
            {
                sb.AppendLine(string.Join(SEPERATOR, row.ToArray()));
            }
    
            return sb.ToString();
        }
    
        public void SaveAs(string path)
        {
            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.Write(_GenerateCSV());
            }
        }
    }
    

提交回复
热议问题