private DataTable ImportCsvToDT(string FilePath)
{
DataTable dt = new DataTable();
StreamReader _Reader = null;
string[] iRows = null;
string[] iCols = null;
string cellContent = "";
try
{
//判斷文件是否存在
if (File.Exists(FilePath))
{
//讀文件
_Reader = new StreamReader(FilePath, Encoding.Default);
string line = "";
//判斷是否有下一行
while (_Reader.Peek()>0)
{
if (line.Length > 0)
{
line += "/" + _Reader.ReadLine();
}
else
{
line += _Reader.ReadLine();
}
}
//行
iRows = line.Split(new Char[]{'/'});
//循環行
for (int iRow = 0; iRow < iRows.Length; iRow++)
{
//列
iCols = iRows[iRow].Split(new Char[] { ','});
DataRow dr = dt.NewRow();
//循環列
for (int iCol = 0; iCol < iCols.Length; iCol++)
{
cellContent = iCols[iCol].ToString();
if (iRow == 0)
{
//添加列頭
dt.Columns.Add(cellContent);
}
else
{
//添加列值
dr[iCol] = cellContent;
}
}
//添加列
if (iRow != 0)
dt.Rows.Add(dr);
}
//判斷列是否合乎要求
if (dt.Columns.Count > 8)
{
for (int i = 9; i < dt.Columns.Count; i++)
{
//當表列大於8時刪除多餘的列
dt.Columns.RemoveAt(i);
}
}
if (dt.Columns.Count < 8)
{
int k = 8 - dt.Columns.Count;
for (int i = 0; i < k; i++)
{
//當表列小於8時刪除多餘的列
dt.Columns.Add(new DataColumn());
}
}
}
}
catch (Exception ex)
{
return null;
}
finally
{
_Reader.Close();
}
return dt;
}