пятница, 23 ноября 2012 г.

CSV и DataTable


Создание и чтение CSV файла.

Первая строка в CSVфайле содержит имена столбцов и типы в формате
name1:String;name2:String;name3:Int32;name4:Decimal;name5:DateTime

Пример:
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
CSV.CreateFile(table, @"c:\test.csv");
DataTable dt = CSV.LoadFile(@"c:\test.csv");

--------------------------------------------------------------------------------------------------------
using System;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

public static class CSV
    {
        public static void CreateFile(DataTable dt, String strFilePath)
        {
            #region Export DataTable to CSV

            using (StreamWriter sw = new StreamWriter(strFilePath, false))
            {
                int iColCount = dt.Columns.Count;

                // First we will write the headers.
                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(String.Format(@"{0}:{1}", dt.Columns[i], dt.Columns[i].DataType.ToString().Replace(@"System.", "")));
                    if (i < iColCount - 1)
                    {
                        sw.Write(";");
                    }
                }
                sw.Write(sw.NewLine);

                // Now write all the rows.
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        else
                        {
                            sw.Write(@"");
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(";");
                        }
                    }
                    sw.Write(sw.NewLine);
                }
                sw.Close();
            }

            #endregion
        }


        public static DataTable LoadFile(String strFilePath)
        {
            if (!File.Exists(strFilePath))
            {
                return null;
            }

            #region Export CSV to DataTable

            DataTable dt = new DataTable();

            FileInfo f = new FileInfo(strFilePath);
            double readSize = 0;

            using (var sr = new StreamReader(strFilePath, System.Text.Encoding.ASCII))
            {
                String line;
                bool setColums = false;
                char[] splRow = new char[] { ';' };
                char[] splCol = new char[] { ':' };

                Int32 cols = 0;
                while (sr.Peek() >= 0)
                {
                    try
                    {
                        line = sr.ReadLine();
                        readSize += line.Length;

                        if (string.IsNullOrEmpty(line)) continue;
                        var values = line.Split(splRow, StringSplitOptions.None);

                        if (!setColums)
                        {
                            setColums = true;
                            cols = values.Length;
                            String colName;
                            Type colType;
                            for (int colNum = 0; colNum < cols; colNum++)
                            {
                                if (values[colNum].IndexOfAny(splCol) != -1)
                                {
                                    var v = values[colNum].Split(splCol);
                                    colName = v[0];
                                    colType = Type.GetType(@"System." + v[1], false, false);
                                    dt.Columns.Add(colName, colType != null ? colType : typeof(String));
                                }
                                else
                                {
                                    dt.Columns.Add(values[colNum]);
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                dt.Rows.Add(values);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message + "\n" + line);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            return dt;

            #endregion
        }
    }

Комментариев нет:

Отправить комментарий