2009-12-20 66 views

回答

2

這裏是a sample

Excel.Application oXL; 
    Excel._Workbook oWB; 
    Excel._Worksheet oSheet; 
    Excel.Range oRng; 


     //Start Excel and get Application object. 
     oXL = new Excel.Application(); 
     oXL.Visible = true; 

     //Get a new workbook. 
     oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); 
     oSheet = (Excel._Worksheet)oWB.ActiveSheet; 

     //Add table headers going cell by cell. 
     oSheet.Cells[1, 1] = "First Name"; 
+2

只是想標記這種方法需要在運行程序的機器上安裝Microsoft Excel。 – empi 2009-12-20 15:26:27

4

下面是一個使用ADO.NET的方法:

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myfile.xls;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"; 
string provider = "System.Data.OleDb"; 
DbProviderFactory factory = DbProviderFactories.GetFactory(provider); 
DbConnection connection = factory.CreateConnection(); 
connection.ConnectionString = connectionString; 
connection.Open(); 
DbCommand command = connection.CreateCommand(); 
command.CommandText = "SELECT * FROM [Sheet1$]" 
DbDataReader reader = command.ExecuteReader(); 
while(reader.read()) { 
    // process row 
} 

ConnectionString.com對連接字符串設置的詳細信息(例如,Excel 2007是)。當您在command上設置commandText屬性時,您可以設置更復雜的查詢(SELECT * from [Sheet1$] where someColumn <> someValue and someOtherColumn > someOtherValue)。

這種方法有一個很好的優點,如果你已經熟悉ADO.NET,你可以使用你在那裏獲得的知識。此外,Excel不需要安裝在機器上。

+0

+1因爲它不需要你安裝excel – TheVillageIdiot 2009-12-20 15:50:01

相關問題