2011-03-26 139 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(); 
}