[C#自學第一天] Excel的讀取和寫入

在ERP定製開發的過程中,很多操作都是和Excel相關的,主要就是學習一些Excel處理的方法, 從而熟悉且靈活使用它。

1)  使用DataReader循環讀取Excel某列的數據:

  1. protected void Button1_Click(object sender, EventArgs e) 
  2.     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\WebSite8\App_Data\Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";  //定義excel的路徑,可以使用完整文件名; 
  3.     DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); //使用他的原因就是對類進行抽象; 具體原理還不是很清楚,使用DbProviderFactory必須引用System.Data.Common;
  4.  
  5.     using (DbConnection connection = factory.CreateConnection())  //定義connection 對象 
  6.     { 
  7.         connection.ConnectionString = connectionString;     //定義連接; 使用DBconnection的ConnectionString屬性; 
  8.  
  9.         using (DbCommand command = connection.CreateCommand())   //定義DbCommand對象; 
  10.         { 
  11.             // Cities$ comes from the name of the worksheet 
  12.             command.CommandText = "SELECT ID,City,State FROM [Cities$]"//定義commandText; 
  13.  
  14.             connection.Open();    
  15.  
  16.             using (DbDataReader dr = command.ExecuteReader())   //定義DbDataReader對象, 通過dr.Read()屬性判斷結束,來遍歷所有列的值;  
  17.             { 
  18.                 while (dr.Read()) 
  19.                 { 
  20.                     Response.Write(dr["ID"].ToString()); 
  21.                     //Response.Write(dr[2].ToString());    //當然也可以通過直接指定第幾列來取具體的值; 
  22.                 } 
  23.             } 
  24.         } 
  25.     } 

 2)  以數據庫訪問的方式,把Excel的數據以放在gridview中顯示:

 

  1. protected void Button2_Click(object sender, EventArgs e) 
  2.     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\WebSite8\App_Data\Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;"""
  3.     try 
  4.     {  
  5.         string sql ="SELECT * FROM [Cities$]" ; 
  6.         OleDbConnection OleConn = new OleDbConnection(connectionString);  //使用OleDbConnection需要引用"using System.Data.OleDb"; 
  7.         OleConn.Open(); 
  8.  
  9.         OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn); //OleDataAdapter和SqlDataAdapter功能類似; 
  10.         DataSet OleDs = new DataSet(); 
  11.         OleDaExcel.Fill(OleDs,"Cities");   
  12.         OleConn.Close(); 
  13.         GridView1.DataSource = OleDs; 
  14.         GridView1.DataBind(); 
  15.          
  16.     } 
  17.     catch (Exception ex) 
  18.     { 
  19.         Response.Write("Fail to bind excel: "+ex.Message); 
  20.     } 

 3) 把數據庫裏面的內容同步到Excel中: 使用Microsoft.Office.Interop.Excel.Application,裏面有清楚的Workbook和Worksheet的定義:

 

  1. protected void Button3_Click(object sender, EventArgs e) 
  2.     { 
  3.         //添加組件,COM裏面的:Microsoft Excel 11.0 Object Library 
  4.         Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
  5.         System.Data.DataTable excelTable = new System.Data.DataTable(); 
  6.  
  7.         SqlConnection sqlconn = new SqlConnection("Data Source=efacsdb;Initial Catalog=whatifdb;User ID=sa; Password=L-BBgD7q"); 
  8.         sqlconn.Open(); 
  9.         SqlDataAdapter sda = new SqlDataAdapter("select top 10 * from t_tt_buyer_group", sqlconn); 
  10.         DataSet ds = new DataSet(); 
  11.         sda.Fill(ds,"table1"); 
  12.         excelTable = ds.Tables["table1"]; 
  13.  
  14.         string filePath ="c:\temp\test.xls"
  15.         try 
  16.         { 
  17.             app.Visible = false
  18.             Workbook wb = app.Workbooks.Add(true); 
  19.             Worksheet ws = app.Worksheets[1] as Worksheet; 
  20.             if (excelTable.Rows.Count > 0) 
  21.             { 
  22.                 int row = 0; 
  23.                 row = excelTable.Rows.Count; 
  24.                 int col = excelTable.Columns.Count; 
  25.                 for (int i= 0; i<row; i++) 
  26.                 { 
  27.                     for (int j=0; j<col; j++) 
  28.                     { 
  29.                         string str = excelTable.Rows[i][j].ToString(); 
  30.                         ws.Cells[i+2,j+1] = str; 
  31.                     } 
  32.                 } 
  33.             } 
  34.  
  35.             int size = excelTable.Columns.Count; 
  36.             for (int i=0;i< size;i++) 
  37.             { 
  38.                ws.Cells[1,1+i] = excelTable.Columns[i].ColumnName; 
  39.             } 
  40.             //不顯示保存和覆蓋的確認提示框: 
  41.             app.DisplayAlerts = false
  42.             app.AlertBeforeOverwriting = false
  43.             //保存工作簿 
  44.             wb.SaveCopyAs(@"C:\temp\test1.xls");  \\如果用wb.save()就會報錯,提示Sheet1.xls無法訪問; 保存時如果文件不存在也會報錯; 
  45.             //保存excel文件 
  46.             //app.SaveWorkspace(filePath); 
  47.             app.Quit(); 
  48.             app=null
  49.         } 
  50.         catch (Exception ex) 
  51.         { 
  52.             Response.Write("export error"+ex.Message); 
  53.         } 
  54.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章