Thursday, July 18, 2013

How to Import data from excel sheet to datatable and bind to listview

Here what we are doing is we have to upload the file into our application and the import data into the data table and then delete the file from our application.
After uploading the document using Fileupload control we have to check weather the upload document is path existing or not,file format is correct or not

Note : excel sheet format should be like this
      Sno      Email
        1         1@1.1
        2         2@2.2

protected void btnImportto_Click(object sender, EventArgs e)
        {
            try
            {
                //Checking weather file exist or not
                if (uploadExcel.HasFile)
                {
                    //checking the weather existing file has extension .xlsx or .xls
                    if (Path.GetExtension(uploadExcel.FileName) == ".xlsx" ||                              Path.GetExtension(uploadExcel.FileName) == ".xls")
                 {
                        //getting path here
                        string filepath = Server.MapPath("~/");
                        //saving into paticular path
                        uploadExcel.SaveAs(filepath + uploadExcel.PostedFile.FileName);
                        //exact file path
                        string relativePath = Server.MapPath("~/" + uploadExcel.PostedFile.FileName);
                        lblStatusmsg.Text = "Upload status: File uploaded!";
                        //importing data from the excel sheet to our application
                        TestExcel(relativePath);
                    }
                    else
                    {
                        lblStatusmsg.Text = "The file you uploaded has invalid extension,Please upload xls or xlsx file";
                    }

                    string filepathtodelete = Server.MapPath("~/"+uploadExcel.PostedFile.FileName);
                    if (uploadExcel.HasFile)
                    {
                        //delete file from the respective path
                        File.Delete(filepathtodelete);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

private void TestExcel(string filePath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbook book = null;
            Range range = null;
            try
            {
                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayAlerts = false;
                string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                //Getting the Excel path

                book = app.Workbooks.Open(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                                  , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                foreach (Worksheet sheet in book.Worksheets)
                {
                    Console.WriteLine(@"Values for Sheet " + sheet.Index);
                    // get a range to work with
                    range = sheet.get_Range("A1", Missing.Value);
                    // get the end of values to the right (will stop at the first empty cell)
                    range = range.get_End(XlDirection.xlToRight);
                    // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                    range = range.get_End(XlDirection.xlDown);
                    // get the address of the bottom, right cell
                    string downAddress = range.get_Address(false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
                    // Get the range, then values from a1
                    range = sheet.get_Range("A1", downAddress);
                    object[,] values = (object[,])range.Value2;
                    // View the values
                    Console.Write("\t");
                    Console.WriteLine();
                    for (int i = 2; i <= values.GetLength(0); i++)
                    {
                        for (int j = 1; j <= values.GetLength(1); j++)
                        {
                            //Console.Write("{0}\t", values[i, j]);
                            System.Data.DataTable dtbulk = new System.Data.DataTable();

                            if (Session["BulkReceipts"] == null)
                            {
                                //here we are creating the colums
                                //Here you can add the columns as your wish
                                dtbulk.Columns.Add("Active", typeof(bool));
                                dtbulk.Columns.Add("Receiptent");
                            }
                            else
                            {
                                dtbulk = (System.Data.DataTable)Session["BulkReceipts"];
                            }
                             //Here we getting paticular colum value or text              
                            String strContains = values[i, j].ToString( );
                            if (strContains.Contains("@"))//Checking weather mailid or not
                            {
                                dtbulk.Rows.Add(true, values[i, j]);
                                //dtbulk = (System.Data.DataTable)Session["Receipts"];
                                Session["BulkReceipts"] = dtbulk;
                                //dtbulk.Rows.Clear();
                            }
                        }
                    }
                    if (Session["BulkReceipts"] != null)
                    {
                        System.Data.DataTable dtbulk = (System.Data.DataTable)Session["BulkReceipts"];
                       //here i am adding the data to listview
                        lvReceiptents.DataSource = dtbulk;
                        lvReceiptents.DataBind();
                    }
                }
            }
            catch (Exception e)
            {
               //Console.WriteLine(e);
            }
            finally
            {
                range = null;
                if (book != null)
                    book.Close(false, Missing.Value, Missing.Value);
                book = null;
                if (app != null)
                    app.Quit();
                app = null;
            }
        }


How to bind the records to a list in MVC


  • The major advantage in MVC is there is no need to write Bulk amount of code. Here by writing the single line of code we can bind the records from database to list....

VIEW::viewlist.aspx:
<body>
    <table>
        <tr>
            <th></th>
            <%--<th>
                EmpID
            </th>--%>
            <th>
                Code
            </th>
            <th>
                Salary
            </th>
            <th>
                CustomerName
            </th>
        </tr>

    <% foreach (var item in Model) { %>
    
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Editcustomer","Customer", new { id =item.EmpID }, new object { })%> |
                <%: Html.ActionLink("Details", "Details", new { id = item.EmpID })%> |
                <%: Html.ActionLink("Delete", "DeleteCustomer", new { id = item.EmpID })%>                
            </td>
           <%-- <td>
                <%: item.EmpID %>
            </td>--%>
            <td>
                <%: item.Code %>
            </td>
            <td>
                <%: item.Salary %>
            </td>
            <td>
                <%: item.CustomerName %>
            </td>
        </tr>
    
    <% } %>

    </table>

    <p>
        <%: Html.ActionLink("Create New", "returntofillcustomer1", "Customer")%>
    </p>

</body>

Controller:: Customer

//Here we are binding the list of customers to list
public ActionResult Viewlist()
        {  
            //here we are returning the list of customers from the model class(from tb_EmpDetails)
            return View(Customer.GetCustomerDetails());
        }

Modelclass:: Customer.cs

//Here we are returning the employee list
 public static List<tb_EmpDetails> GetCustomerDetails( )
        {
            var customer1 = new CustomerEntities1( );//CustomerEntities1 is nothing but Database (.emdf) file
            //adding all the records from tb_EmpDetails to the list and returning the list
            return customer1.tb_EmpDetails.ToList( );
        }







Monday, July 8, 2013

How to insert data into table in MVC

After filling the form and click the submit, definately  the the form will post some data
View: fillcustomer1.aspx
<body>
    <% using (Html.BeginForm("FillCustomer1", "Customer", FormMethod.Post))
       {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Code) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Code) %>
                <%: Html.ValidationMessageFor(model => model.Code) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CustomerName) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CustomerName) %>
                <%: Html.ValidationMessageFor(model => model.CustomerName) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Salary) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Salary) %>
                <%: Html.ValidationMessageFor(model => model.Salary) %>
            </div>
         
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Viewlist","Customer")%>
    </div>
</body>

Now we have to insert the data into database:

Controller: Customer: in the below code CustomerEntities1  is nothing but our database(.emdx) file

        [Authorize] //Here we are just designing our action with authorize for form authentications
        [HttpPost]
        public ActionResult FillCustomer1(tb_EmpDetails emp_details)
        {
            //here we are using the .edmx(copy of database) file.....
            using (CustomerEntities1 customerdetails = new CustomerEntities1())
            {
                if (ModelState.IsValid)
                {
                    //here we are passing(adding) the  values to table using addtotable
                    customerdetails.AddTotb_EmpDetails(emp_details);
                    //after adding the values to table save the table
                    customerdetails.SaveChanges();
                    //redirecting from one action to another action
                    return RedirectToAction("Viewlist", "Customer");
                }
                else
                {
                    ModelState.AddModelError("", "Please enter fields properly");
                    //Content("<script language='javascript' type='text/javascript'>alert('Please enter fields properly');</script>");
                    return View();                      
                }
            }

        }