본문 바로가기
프로그래밍/C Sharp

[ C# ] DataTable CSV 읽고 쓰기

by jeong-f 2022. 1. 13.
반응형

테스트 환경

VisualStudio  2008 / 2010

CSV 파일 내용

CSV 열기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
        public DataTable LoadCSV(string fileName )
        {
            DataTable table = new DataTable();
 
            string[] buff = File.ReadAllLines(fileNae, Encoding.UTF8);
            
            foreach (string d in buff)
            {
                string[] split = d.Split(',');
 
                if (split.Length > 0)
                {
                    if (split[0== "X")
                    {
                        foreach (string colName in split)
                        {
                            table .Columns.Add(colName);   
                        }
                    }
                    else
                    {
                        table .Rows.Add(split);
                    }
                }
            }
 
            return table;
        }
cs

CSV 저장

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public bool SaveCSV(string fileName, DataTable table)
        {
            List<string> buff = new List<string>();
 
            string[] columnNames = table.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();
 
            string line = string.Join(",", columnNames);
            buff.Add(line);
 
            foreach (DataRow row in table.Rows)
            {
                string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
 
                line = string.Join(",", fields);
                buff.Add(line);
            }
 
            File.WriteAllLines(fileName, buff.ToArray(), Encoding.UTF8);
 
 
            return true;
        }
cs

 

반응형

댓글