[엑셀] C# 작업 엑셀(내보내기 가져오기)

7618 단어 Excel
/// <summary> 

///  Excel  

/// </summary> 

/// <param name="Path"> </param> 

/// <returns> </returns> 

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; 

} 





/// <summary> 

///  Excel  

/// </summary> 

/// <param name="Path"> </param> 

public bool SaveFP2toExcel(string Path) 

{ 

try 

{ 

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

OleDbConnection conn = new OleDbConnection(strConn); 

conn.Open(); 

System.Data.OleDb.OleDbCommand cmd=new OleDbCommand (); 

cmd.Connection =conn; 

//cmd.CommandText ="UPDATE [sheet1$] SET  ='2005-01-01' WHERE  =' '"; 

//cmd.ExecuteNonQuery (); 

for(int i=0;i<fp2.Sheets [0].RowCount -1;i++) 

{ 

if(fp2.Sheets [0].Cells[i,0].Text!="") 

{ 

cmd.CommandText ="INSERT INTO [sheet1$] ( , , , , , ) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+ 

fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+ 

"','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')"; 

cmd.ExecuteNonQuery (); 

} 

} 

conn.Close (); 

return true; 

} 

catch(System.Data.OleDb.OleDbException ex) 

{ 

System.Diagnostics.Debug.WriteLine (" Excel :"+ex.Message ); 

} 

return false; 

}

좋은 웹페이지 즐겨찾기