This repository has been archived by the owner on Mar 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVParser.cs
91 lines (87 loc) · 3.32 KB
/
CSVParser.cs
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Microsoft.VisualBasic.FileIO;
//using System.Diagnostics;
using System.Collections;
namespace SWeight
{
class CSVParser
{
public static DataTable CSV2DataTable(string path)
{
int cnt = 0;
var dt = new DataTable();
DataColumn dc = new DataColumn("num", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("ind", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("sli,g", typeof(string));
dt.Columns.Add(dc);
dc = new DataColumn("lli,g", typeof(string));
dt.Columns.Add(dc);
if (!File.Exists(path) || Path.GetExtension(path) != ".ves")
{
MessageBox.Show($"Файл не существует или не правильное расширение - ({Path.GetExtension(path)})", "Error!" ,MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
//TODO: should I use here convertation to UTF (or more smart checks)
using (TextFieldParser parser = new TextFieldParser(path, System.Text.Encoding.GetEncoding("windows-1251")))
{
parser.Delimiters = new string[] { "\t" };
while (true)
{
string[] parts = parser.ReadFields();
if (parts == null)
break;
if (parts.Length != 1)
{
if (cnt > 1) // skip header
{
DataRow dr = dt.NewRow();
for (var i = 0; i < 4; ++i)
dr[i] = parts[i];
dt.Rows.Add(dr);
}
cnt++;
}
}
}
return dt;
}
public static void DataGridView2CSV(DataGridView dgv,ArrayList header, string path, string AddToNum="")
{
using (StreamWriter sW = new StreamWriter(path))
{
string delim = "\t";
string val = "";
foreach (string head in header)
sW.WriteLine(head);
for (int row = 0; row < dgv.RowCount; ++row)
{
string lines = (row + 1).ToString("D2");
//we save only first three columns, so instead dgv.ColumnCount we will use just 3
for (int col = 0; col < dgv.ColumnCount; ++col)
{
if (col == 1) continue;
if (col == 0)
delim += AddToNum;
val = dgv.Rows[row].Cells[col].Value.ToString();
if (string.IsNullOrEmpty(val))
val = "0";
lines += (string.IsNullOrEmpty(lines) ? "" : delim) + val;
if (col == 0)
delim = "\t";
}
sW.WriteLine(lines);
}
sW.Close();
}
}
}
}