1. 程式人生 > >讀取csv檔案內容到DataTable

讀取csv檔案內容到DataTable


int intColCount = 0;
bool blnFlag = true;
DataTable mydt = new DataTable("myTableName");

DataColumn mydc;
DataRow mydr;

string strpath = ""; //cvs檔案路徑
string strline;
string [] aryline;

System.IO.StreamReader mysr = new System.IO.StreamReader(strpath);

while((strline = mysr.ReadLine()) != null)
{
aryline = strline.Split(new char[]{','});

if (blnFlag)
{
blnFlag = false;
intColCount = aryline.Length;
for (int i = 0; i < aryline.Length; i++)
{
mydc = new DataColumn(aryline[i]);
mydt.Columns.Add(mydc);
}
}

mydr = mydt.NewRow();
for (int i = 0; i < intColCount; i++)
{
mydr[i] = aryline[i];
}
mydt.Rows.Add(mydr);
}