Question

I am uploading excel from xls file in mvc5 i have following method

public ActionResult Importexcel()
        {


            if (Request.Files["FileUpload1"].ContentLength > 0)
            {
                string fileExtension =
                                     System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);

                if (fileExtension == ".xls" || fileExtension == ".xlsx")
                {
                    // Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there. 
                    string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
                    if (System.IO.File.Exists(path1))
                        System.IO.File.Delete(path1);
                    Request.Files["FileUpload1"].SaveAs(path1);
                    string sqlConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
                   //Create Connection to Excel work book and add oledb namespace
                    OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
                    excelConnection.Open();
                    DataTable dt = new DataTable();

                    dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    if (dt == null)
                    {
                        return null;
                    }

                    String[] excelSheets = new String[dt.Rows.Count];
                    int t = 0;
                    //excel data saves in temp file here.
                    foreach (DataRow row in dt.Rows)
                    {
                        excelSheets[t] = row["TABLE_NAME"].ToString();
                        t++;
                    }
                    OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
                    DataSet ds = new DataSet();

                    string query = string.Format("Select * from [{0}]", excelSheets[0]);
                    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                    {
                        dataAdapter.Fill(ds);
                    }

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {

                        SqlConnection sqlc = new SqlConnection();
                        sqlc.ConnectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Planetskool-20140309125429.mdf;Initial Catalog=aspnet-Planetskool-20140309125429;Integrated Security=True";
                        SqlCommand cmd2 = new SqlCommand("INSERT INTO UserInfo (UserInfoID, GraphID, UserCreatorId,UserLevelEnumId,Birthdate,Zipcode,UserLevel,UserID)  VALUES(@UserInfoID, @GraphID, @UserCreatorId,@UserLevelEnumId,@Birthdate,@Zipcode,@UserLevel,@UserID)", sqlc);//@OB_ID is indentity primary key
                        cmd2.Parameters.Add("@UserInfoID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserInfoID"].ToString());
                        cmd2.Parameters.Add("@GraphID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["GraphID"].ToString());
                        cmd2.Parameters.Add("@UserCreatorId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserCreatorId"].ToString());
                        cmd2.Parameters.Add("@UserLevelEnumId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserLevelEnumId"].ToString());
                       // cmd2.Parameters.Add("@Birthdate", SqlDbType.DateTime).Value = DateTime.UtcNow.ToLocalTime();
                        cmd2.Parameters.Add("@Zipcode", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
                        cmd2.Parameters.Add("@UserLevel", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
                        cmd2.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
                        sqlc.Open();
                        cmd2.ExecuteNonQuery();
                        sqlc.Close();

                        //db.StudentRecords.Add(model);
                        //db.SaveChanges();
                    }

                    return RedirectToAction("Index");
                }


            }

when i am uploading the file i am getting only 1 rows in my database i have debug the rows count in visual studio i am geeting total rows but not able to get it in my database

Was it helpful?

Solution

Use Microsoft.Office.Interop.Excel your may as like below... it may help you

public void ImportXLX()
    {


                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

                Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(@"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                        Type.Missing, Type.Missing);

                int workSheetCounts = wb.Worksheets.Count;

                for (int sheetCounter = 1; sheetCounter <= workSheetCounts; sheetCounter++)
                {
                    Microsoft.Office.Interop.Excel.Worksheet workSheet = wb.Sheets[sheetCounter];

                    Range excelRange = workSheet.UsedRange;
                    Range objRange = null;

                    int rowCountForHeight = 0;
                    double totalColHeight = 0;
                    double totalRowWidth = 0;

                    foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
                    {
                        rowCountForHeight++;
                        int colCount = 0;
                        foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
                        {
                            colCount++;
                            objRange = workSheet.Cells[rowCountForHeight, colCount];
                            double height = 0;

                            if (objRange.MergeCells)
                            {
                                Debug.Write("CellsMerged \n");
                                height = ((Range)objRange.MergeArea[1, 1]).Height;
                            }
                            else
                            {
                                Debug.Write("CellsMergedNot \n");
                                height = objRange.Height;
                            }

                            totalColHeight = totalColHeight + height;
                        }
                    }

                    int rowCount = 0;
                    foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
                    {
                        rowCount++;
                        totalRowWidth = row.Width;
                        int colCount = 0;

                        foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
                        {
                            colCount++;
                            objRange = workSheet.Cells[rowCount, colCount];

                            double width = 0;
                            double height = 0;
                            string colVal = null;

                            if (objRange.MergeCells)
                            {
                                colVal = Convert.ToString(((Range)objRange.MergeArea[1, 1]).Text).Trim();
                                width = objRange.MergeArea.Width;
                                height = objRange.MergeArea.Height;


                            }
                            else
                            {
                                colVal = Convert.ToString(objRange.Text).Trim();
                                width = objRange.Width;
                                height = objRange.Height;
                            }
                            Debug.Write("objRange = " + objRange + " rowCount = " + rowCount + " Width = " + width + " height = " + height + "TotalColumnWidth = " + totalRowWidth + "TotalRowHeight = " + totalColHeight + " \n ");
                        }
                    }
                }
                app.Quit();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top