前些日子,有很多朋友說需要c#導出到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;
}
這種方法目前最有效,如果有不明白的地方可以來信交流
a
新聞熱點
疑難解答