方法一,純文本方法,即把該文件當做文本文件讀取
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);
}
方法二、當做一個數據源讀取,常用的sql語句都能執行的
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:csv;Extended Properties=Text;"))
{
DataTable dtTable = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Test.csv]", conn);
try
{
adapter.Fill(dtTable);
}
catch (Exception ex)
{
dtTable = new DataTable();
}
this.GridView1.DataSource = dtTable;