2011-03-26 148 views
0

如何導入Excel文件到C#項目?導入Excel文件

+0

你想將其添加到項目或讀出值成C#程序? (例如將其轉換爲DataTable) – digEmAll 2011-03-26 15:09:01

+0

我們需要更多的細節。你究竟想要做什麼?你最終想要完成什麼? – 2011-03-26 15:09:07

+0

我想在我的項目中編輯這些數據 – 2011-03-26 15:19:16

回答

0

確保它位於項目目錄中的正確文件夾中,然後(假設您正在使用Visual Studio)單擊解決方案資源管理器中的顯示所有文件(它是工具頂部的小按鈕之一),然後右鍵單擊現在應顯示的ecel文件,然後單擊添加到項目。

0

注意路徑Excel文件是動態設置的:

// using System.Data.OleDb 
OleDbConnection ExcelConection = null; 
OleDbCommand ExcelCommand = null; 
OleDbDataReader ExcelReader = null; 
OleDbConnectionStringBuilder OleStringBuilder = null; 

try 
{ 
    OleStringBuilder = 
     new OleDbConnectionStringBuilder(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"); 
    OleStringBuilder.DataSource = MapPath(@"~\App_Datav\MyExcelWorksheet.xls"); 

    ExcelConection = new OleDbConnection(); 
    ExcelConection.ConnectionString = OleStringBuilder.ConnectionString; 

    ExcelCommand = new OleDbCommand(); 
    ExcelCommand.Connection = ExcelConection; 
    ExcelCommand.CommandText = "Select * From [Sheet1$]"; 

    ExcelConection.Open(); 
    ExcelReader = ExcelCommand.ExecuteReader(); 

    GridView1.DataSource = ExcelReader; 
    GridView1.DataBind(); 
} 
catch (Exception Args) 
{ 
    LabelErrorMsg.Text = "Could not open Excel file: " + Args.Message; 
} 
finally 
{ 
    if (ExcelCommand != null) 
     ExcelCommand.Dispose(); 
    if (ExcelReader != null) 
     ExcelReader.Dispose(); 
    if (ExcelConection != null) 
     ExcelConection.Dispose(); 
}