开发者

import Excel file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad开发者_开发问答, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How can I import Excel file to C# project ?


You can use Office Object Model to work with Excel sheets. Add a reference to Microsoft.Excel.Interop assembly. You can use this reference for working with excel sheets.


Make sure it is in the correct folder in the project directory, then (assuming you are using Visual Studio) click on the show all files in the solution explorer (it is one of the small buttons at the top of the tool) and then right click the ecel file that should now show up and click add to project.


Note the path to the Excel file is set dynamically:

// 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜