在CSV文件导入到数据库时使用过的代码

时间:2021-12-27 20:39:15
#region  简单CSV文件读取方式(无特殊情况的CSV文件)

public static DataTable ImportCSV(string filePath)
{
DataTable dt = new DataTable();

int lsi = 0;
char cv = '\r';
bool HeadYes = true;//第一行是否为标题
StreamReader fileReader = new StreamReader(filePath, Encoding.Default);
while (fileReader.EndOfStream == false)
{
string line = fileReader.ReadLine();
string[] y = line.Split(cv);
//第一行为标题行
if (HeadYes == true)
{
//第一行
if (lsi == 0)
{
for (int i = 0; i < y.Length; i++)
{
dt.Columns.Add(y[i].Trim().ToString());
}
lsi++;
}
//从第二列开始为数据列
else
{
DataRow dr = dt.NewRow();
for (int i = 0; i < y.Length; i++)
{
dr[i] = y[i].Trim();
}
dt.Rows.Add(dr);
}
}
//第一行不为标题行
else
{
if (lsi == 0)
{
for (int i = 0; i < y.Length; i++)
{
dt.Columns.Add(i.ToString());
}
lsi++;
}

DataRow dr = dt.NewRow();
for (int i = 0; i < y.Length; i++)
{
dr[i] = y[i].Trim();
}
dt.Rows.Add(dr);
}
}
return dt;
}
#endregion


#region 无回车符的CSV文件读取方式
public void GetCsv(string filePath)
{
string s = string.Empty;
string src = string.Empty;
SortedList sl = new SortedList();
StreamReader fs = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read), Encoding.Default);
while (!string.IsNullOrEmpty(s = fs.ReadLine()))
{
if (!string.IsNullOrEmpty(s))
{
src = s.Replace("\"\"", "'");
MatchCollection col = Regex.Matches(src, ",\"([^\"]+)\",", RegexOptions.ExplicitCapture);
IEnumerator ie = col.GetEnumerator();
while (ie.MoveNext())
{
string patn = ie.Current.ToString();
int key = src.Substring(0, src.IndexOf(patn)).Split(',').Length;
if (!sl.ContainsKey(key))
{
sl.Add(key, patn.Trim(new char[] { ',', '"' }).Replace("'", "\""));
src = src.Replace(patn, ",,");
}
}

string[] arr = src.Split(',');
for (int i = 0; i < arr.Length; i++)
{
if (!sl.ContainsKey(i))
sl.Add(i, arr[i]);
}
IDictionaryEnumerator ienum = sl.GetEnumerator();
while (ienum.MoveNext())
{
var strKey = ienum.Key;
var strValue = ienum.Value.ToString().Replace("'", "\"");
}
sl.Clear();
src = string.Empty;
}
}
fs.Close();
}
#endregion