import Excel file [closed]
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();
}
精彩评论