CSVFileHelper.cs
5.6 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using log4net;
using Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace OnLineStore.Common
{
public class CSVFileHelper
{
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 将DataTable中数据写入到CSV文件中
/// </summary>
/// <param name="dt">提供保存数据的DataTable</param>
/// <param name="fileName">CSV的文件路径</param>
public static void SaveCSV(DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo(fullPath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
string data = "";
//写出列名称
for (int i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName.ToString();
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dt.Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
{
str = string.Format("\"{0}\"", str);
}
data += str;
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
//DialogResult result = MessageBox.Show("CSV文件保存成功!");
}
public static string[][] Read(string fullname)
{
if (!File.Exists(fullname)) return new string[][] { };
var lines = File.ReadAllLines(fullname).Skip(1);
var list=new List<string[]>();
var builder = new StringBuilder();
foreach (var line in lines)
{
builder=new StringBuilder ();
var comma = false;
var array = line.ToCharArray();
var values = new List<string>();
var length = array.Length - 1;
var index = 0;
while (index < length)
{
var item = array[index++];
switch (item)
{
case ',':
if (comma)
{
builder.Append(item);
}
else
{
values.Add(builder.ToString());
builder = new StringBuilder();
}
break;
case '"':
comma = !comma;
break;
default:
builder.Append(item);
break;
}
}
var count = values.Count;
if (count == 0) continue;
list.Add(values.ToArray());
}
return list.ToArray();
}
//public static List<StoreBagConfig> ReadList(string fullname)
//{
// List<StoreBagConfig> result = new List<StoreBagConfig>();
// if (!File.Exists(fullname)) {
// return result;
// }
// var lines = File.ReadAllLines(fullname).Skip(1);
// var list = new List<string[]>();
// int index=0;
// foreach (var line in lines)
// {
// var array = line.Split(',');
// var length = array.Length ;
// if (length == 5)
// {
// int col = Int32.Parse(array[0]);
// int row = Int32.Parse(array[1]);
// int axisPosition = Int32.Parse(array[2]);
// int highPosition = Int32.Parse(array[3]);
// int lowPosition = Int32.Parse(array[4]);
// StoreBagConfig config = new StoreBagConfig();
// config.AxisPostion = axisPosition;
// config.BagColoum = col;
// config.CsvRowIndex = index;
// config.HighPostion = highPosition;
// config.LowPosition = lowPosition;
// config.BagRow = row;
// result.Add(config);
// }
// else
// {
// LogUtil.error(LOGGER,"读取csv,index="+index+",数据格式不匹配!,line="+line);
// }
// index++;
// }
// return result;
//}
}
}