Wednesday 28 May 2014

Getting Data table from the Excel Sheet Using C#

        string connectionString = "";
        bool flag = true;
        object value;
        try
        {

            string fileName = Path.GetFileName(fb_master.PostedFile.FileName);
            string fileExtension = Path.GetExtension(fb_master.PostedFile.FileName);
            string folder = ConfigurationManager.AppSettings["TargetFiles"];
            string fileLocation = ConfigurationManager.AppSettings["TargetFiles"]+System.DateTime.Today.ToString("dd-MMyyyy")+"_"+ fileName;
            DirectoryInfo dir = new DirectoryInfo(folder);
            if (!dir.Exists)
                dir.Create();

            fb_master.SaveAs(fileLocation);

            if (fb_master.HasFile)
            {
                //Check whether file extension is xls or xslx
                if (fileExtension == ".xls")
                {
                    connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                }
                else if (fileExtension == ".xlsx")
                {
                    //connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
                    connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
                }

                //Create OleDB Connection and OleDb Command
                OleDbConnection con = new OleDbConnection(connectionString);
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = con;
                OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
                DataTable dtExcelRecords = new DataTable();
                con.Open();
                DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
                cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "] where Finyear is not null ";
                dAdapter.SelectCommand = cmd;
                dAdapter.Fill(dtExcelRecords);
                con.Close();
          }

        }
        catch (Exception ex)
        {
            UserMessage.ShowUserMessage("Excel file cannot be uploaded.please check the data in Excel file.It may contains Null values.");
            _gb.ErrorLog(ex.Message);
        }