天天看點

DataTable 與 Excel檔案(CSV)互相轉化

在一個項目中,需要從Excel檔案導入資料然後再datagridview上顯示,同時也需要右鍵datagridview時可以将資料另存為excel檔案,于是寫了這兩個工具方法。本文提供了兩個方法用于Excel和DataTable之間互相轉化。

1, 從Excel檔案、CSV檔案導入到DataTable:

  1. public static DataTable csvToDataTable(string file)  
  2.  {  
  3.      string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;'"; // Excel file  
  4.  if(file.EndsWith(".csv"))  
  5.          strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;'"; // csv file:HDR=Yes-- first line is header  
  6.      OleDbConnection oleConn = new OleDbConnection(strConn);  
  7.      oleConn.Open();  
  8.      DataTable sheets = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  9.      if (sheets == null || sheets.Rows.Count < 1)  
  10.      {  
  11.          return null;  
  12.      }  
  13.      String fileName = sheets.Rows[0]["TABLE_NAME"].ToString(); // sheets.Rows[0] -- first sheet of excel  
  14.  if(file.EndsWith(".csv"))  
  15.   fileName = file.Substring(file.LastIndexOf("/"));  
  16.      string olestr = "select * from [" + fileName + "]";  
  17.      if (file.EndsWith(".csv"))  
  18.          olestr = "select * from [" + fileName + "]";  
  19.      OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);  
  20.      oleComm.Connection = oleConn;  
  21.      OleDbDataAdapter oleDa = new OleDbDataAdapter();  
  22.      oleDa.SelectCommand = oleComm;  
  23.      DataSet ds = new DataSet();  
  24.      oleDa.Fill(ds);  
  25.      oleConn.Close();  
  26.      return ds.Tables[0];  
  27.  }  

2,DataTable到出到CSV檔案:

  1. public static void dataTableToCsv(DataTable table, string file)  
  2.         {  
  3.             string title = "";  
  4.             FileStream fs = new FileStream(file, FileMode.Create);  
  5.             StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);  
  6.             for (int i=0; i<table.Columns.Count; i++)  
  7.             {  
  8.                 title += table.Columns[i].ColumnName + ",";  
  9.             }  
  10.             title = title.Substring(0, title.Length - 1) + "\n";  
  11.             sw.Write(title);  
  12.             foreach (DataRow row in table.Rows)  
  13.             {  
  14.                 string line = "";  
  15.                 for (int i = 0; i < table.Columns.Count; i++)  
  16.                 {  
  17.                     line += row[i].ToString() + ",";  
  18.                 }  
  19.                 line = line.Substring(0, line.Length - 1) + "\n";  
  20.                 sw.Write(line);  
  21.             }  
  22.             sw.Close();  
  23.             fs.Close();  
  24.         }  
  25.     }  

轉載于:https://blog.51cto.com/babyhe/407065