C#操作Excel(导入导出)

 1/// <summary>
 2/// 读取Excel文档
 3/// </summary>
 4/// <param name="Path">文件名称</param>
 5/// <returns>返回一个数据集</returns>

 6public DataSet ExcelToDS(string Path)
 7{
 8string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
 9OleDbConnection conn = new OleDbConnection(strConn);
10conn.Open();
11string strExcel = "";
12OleDbDataAdapter myCommand = null;
13DataSet ds = null;
14strExcel="select * from [sheet1$]";
15myCommand = new OleDbDataAdapter(strExcel, strConn);
16ds = new DataSet();
17myCommand.Fill(ds,"table1");
18return ds;
19}

20
21
22/// <summary>
23/// 写入Excel文档
24/// </summary>
25/// <param name="Path">文件名称</param>

26public bool SaveFP2toExcel(string Path)
27{
28try
29{
30string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
31OleDbConnection conn = new OleDbConnection(strConn);
32conn.Open();
33System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();
34cmd.Connection =conn;
35//cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'";
36//cmd.ExecuteNonQuery ();
37for(int i=0;i<fp2.Sheets [0].RowCount -1;i++)
38{
39if(fp2.Sheets [0].Cells[i,0].Text!="")
40{
41cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+
42fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+
43"','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";
44cmd.ExecuteNonQuery ();
45}

46}

47conn.Close ();
48return true;
49}

50catch(System.Data.OleDb.OleDbException ex)
51{
52System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );
53}

54return false;
55}
posted @ 2008-04-11 10:59  jdkbean  阅读(242)  评论(0)    收藏  举报