天天看點

EXCEL讀取與寫入資料的最佳方案[轉]

public DataSet ExcelToDS(string Path) 

{ 

 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 

 OleDbConnection conn = new OleDbConnection(strConn); 

 conn.Open();   

 string strExcel = "";    

 OleDbDataAdapter myCommand = null; 

 DataSet ds = null; 

 strExcel="select * from [sheet1$]"; 

 myCommand = new OleDbDataAdapter(strExcel, strConn); 

 ds = new DataSet(); 

 myCommand.Fill(ds,"table1");    

 return ds; 

} 

對于EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到 

 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 

 OleDbConnection conn = new OleDbConnection(strConn); 

 DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null); 

 string tableName=schemaTable.Rows[0][2].ToString().Trim();   

Excel檔案的寫入 

public void DSToExcel(string Path,DataSet oldds) 

{ 

 //先得到彙總EXCEL的DataSet 主要目的是獲得EXCEL在DataSet中的結構 

 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ;  

 OleDbConnection myConn = new OleDbConnection(strCon) ; 

 string strCom="select * from [Sheet1$]"; 

 myConn.Open ( ) ; 

 OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ; 

 ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand); 

 //QuotePrefix和QuoteSuffix主要是對builder生成InsertComment指令時使用。 

 builder.QuotePrefix="[";     //擷取insert語句中保留字元(起始位置) 

 builder.QuoteSuffix="]"; //擷取insert語句中保留字元(結束位置) 

 DataSet newds=new DataSet(); 

 myCommand.Fill(newds ,"Table1") ; 

 for(int i=0;i<oldds.Tables[0].Rows.Count;i++) 

 { 

  //在這裡不能使用ImportRow方法将一行導入到news中,因為ImportRow将保留原來DataRow的所有設定(DataRowState狀态不變)。在使用ImportRow後newds内有值,但不能更新到Excel中因為所有導入行的DataRowState!=Added 

  DataRow nrow=aDataSet.Tables["Table1"].NewRow(); 

  for(int j=0;j<newds.Tables[0].Columns.Count;j++) 

  { 

   nrow[j]=oldds.Tables[0].Rows[i][j]; 

  } 

  newds.Tables["Table1"].Rows.Add(nrow); 

 } 

 myCommand.Update(newds,"Table1"); 

 myConn.Close(); 

}