2012-05-15 75 views
0

我有一個放在程序調試文件夾中的excel文件,例如C#project/bin/debug。C#如何在excel特定行中保存文本框信息?

我有WinForm 2文本框,並保存按鈕。用戶必須在textbox1中輸入他的姓名,並在texbox2中輸入他的姓氏,並通過單擊保存進行保存。

我的問題是,如何使textbox1輸入保存在行A2在Excel中和textbox2輸入保存在行B2當用戶點擊保存?

該excel文件不應該是可見的,它應該自動保存文件後,用戶點擊保存。

任何人都可以幫助我嗎?代碼示例或指南鏈接將非常有用。

+0

您可以。在這裏解釋[Excel Interop](http://www.dotnetperls.com/excel) –

+0

看看這個http://www.aspsnippets.com/Articles/Export-Data-to-Excel-Sheet-using-ADO .Net-and-C.aspx –

+0

我也建議看看我已經使用過很多次的Excel庫項目。我發現它比interop庫更容易使用:http://code.google.com/p/excellibrary/祝您好運! –

回答

0

您可以使用OleDb對象處理Excel文件。

using System; 
using System.Data; 
using System.Data.OleDb; 

public static class Program 
{ 
    ///This is a very basic example of how to use OleDb objects to edit spreadsheets. 
    /// For more advanced operations, look into using OleDb with DataSets/DataTables. 
    public static void Main(string[] args) 
    { 
     string Filename = "C:\\test.xls"; 
     //If you are using xls format, use this connection string. 
     string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Filename + ";Extended Properties=\"Excel 8.0;HDR=NO;\""; 
     //If you are using xlsx format, use this connection string. 
     //string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO\""; 

     string Name_Value = "First Name"; 
     string Surname_Value = "Surname"; 

     string SQL1 = "UPDATE [Sheet1$A2:A2] SET F1='" + Name_Value + "'"; 
     string SQL2 = "UPDATE [Sheet1$B2:B2] SET F1='" + Surname_Value + "'"; 

     using(OleDbConnection Connection = new OleDbConnection(ConnectionString)) 
     { 
      Connection.Open(); 
      using(OleDbCommand cmd1 = new OleDbCommand(SQL1,Connection)) 
      { 
       cmd1.ExecuteNonQuery(); 
      } 
      using(OleDbCommand cmd2 = new OleDbCommand(SQL2,Connection)) 
      { 
       cmd2.ExecuteNonQuery(); 
      } 
     } 
    } 
} 
相關問題