Introduction
I have one Excel file to be generated from a database, it is available in the attachment with the name bbbb.xlsx.
So first we will convert the Excel data into a DataTable.
Here is the sample code:
- protected void btnUpload_Click(object sender, EventArgs e)
- {
- if (FileUpload1.HasFile)
- {
- string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
- string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
- string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
- string FilePath = Server.MapPath(FolderPath + FileName);
- FileUpload1.SaveAs(FilePath);
- Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
- }
- }
- private void Import_To_Grid(string FilePath, string Extension, string isHDR)
- {
- string conStr = "";
- switch (Extension)
- {
- case ".xls": //Excel 97-03
- conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
- break;
- case ".xlsx": //Excel 07
- conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
- break;
- }
- conStr = String.Format(conStr, FilePath, isHDR);
- OleDbConnection connExcel = new OleDbConnection(conStr);
- OleDbCommand cmdExcel = new OleDbCommand();
- OleDbDataAdapter oda = new OleDbDataAdapter();
- DataTable dt = new DataTable();
- cmdExcel.Connection = connExcel;
- //Get the name of First Sheet
- connExcel.Open();
- DataTable dtExcelSchema;
- dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
- string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
- connExcel.Close();
- //Read Data from First Sheet
- connExcel.Open();
- cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
- oda.SelectCommand = cmdExcel;
- oda.Fill(dt);
- connExcel.Close();
- }
The code above uses a File Upload Control to export an Excel sheet into a DataTable. If the file extension is .xls then it is treated as a (up to) 2003 version but if the file extension is .xlsx then it is treated as a 2007 (and above) version. So finally in this step we must send the data into the data table.



Faisal SaghirPosted Aug 11, 2015, 3:57 AM
great job
Dinesh BeniwalPosted Sep 24, 2014, 10:22 AM
Good start Hanumantharao, welcome to C# Corner.