Thursday, 30 July 2020

C# Code for Move Data From Excel to Database File Using Console Application

Move Data From Excel to Database Sheet by Using Console Application In C#

C# Code for Move the data by using  C# code.Create a table in SQL server next open the Microsoft Visual Studio IDE  Create the new c# Console application then right click on the solution go to manage nuget package search the spreadsheet excel sheet library and install that package.

n sql create same fields table as tbl_students in Database

Goto solution explorer->right click on

//program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.Openxml.Packaging
using DocumentFormat.Openxml.Spreadsheet;
using System.Data.Sqlclient
using System.Data;
using System.Configuration;
using System.IO.Packaging;

namespace ExceltoTable
 {
    class Program
       {
           static void Main(string[],args)
             {
                  try
                       {
                          string path = @"C:\Users\sample.xlsx";
                          string constr = (@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source="+path+";Extended Properties = Excel 12.0;");

OleDbConnection oconn = new OleDbConnection(constr);
OleDbConnection conn = new OleDbConnection(constr);
oconn.Open();
OleDbCommand olcmd = new OleDbCommand("select * from sheet1$",conn);
OleDbDataAdapter oda = new OleDbDataAdapter(olcmd);
DataTable dt = new DataTable();
oda.Fill(dt);
oconn.Close();
SqlConnection  sqlcon = new SqlConnection(@"Data Source=.....");
sqlcon.Open();
using(SqlBulkCopy bc = new SqlBulkCopy(sqlcon))
 {
    bc.DestinationTableName = "tblname";
      foreach(var column in dt.Columns)
         bc.ColumnMappings.Add(column.ToString(),column.ToString())
     bc.WriteToServer(dt);
}
sqlconn.Close();
}
catch(Exception ex)
{
throw ex;
}
}
}
}


Tuesday, 16 June 2020

Read the Text file and print the Data using Console Application

C# Code for Read the data and print the data on console window.
Console application for print the data from the text file using the C# console application in Microsoft Visual Studio IDE.

//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;

namespace Readfile
 {
   class Program
     {
       static void Main(string[],args)
         {
                  string textfile = System.IO.File.ReadAllText(@"C:\Users\textfile.txt");

            Console.WriteLine("text file is {0} ",textfile);

                         string textfilelines = System.IO.File.ReadAllLines(@"C:\Users\textfile.txt");
                       foreach(string lines in textfilelines )
                   {
                               Console.WriteLine("lines are\t",lines);
                   }
               Console.WriteLine("press any key to continue..");
               Console.ReadKey();
}






                           

ASP.NET Code for Move Data From Database to Excel File Using Web Application

Move Data From Database to Excel Sheet by Using Web Application In ASP.NET

Asp.net Code for Move the data by using User Interface with C# code.Create a table in SQL server next open the Microsoft Visual Studio IDE  Create the new Asp.net web application then right click on the solution go to manage nuget package search the EPPlus excel sheet library and install that package.

n sql create table as tbl_students in Database

Goto solution explorer->right click on the project->select Mange Nuget Package-> install the EPPlus package

//UIexcel.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sqlclient
using System.Data;
using System.Configuration;
using System.IO;
using System.OfficeOpenXml;

namespace MovedatawithUI
{
   public partial class UIexcel : System.Web.UI.Page
      {
         protected void Page_Load(object sender, EventArgs e)
            {
               if(!IsPostBack)
                 {
                   txt1.Focus();
                 }
            }
         protected void btn1_click(object sender, EventArgs e)
            {
                  string constr = ConfigurationManager.ConnectionStrings["dbconn"].Connectionstring.Tostring();

SqlConnection con = new SqlConnection(constr);

  SqlCommand cmd = new SqlCommand("insert into   tbl_tablename(id,name,address)       values(@id,@name,@address)",con);
   cmd.Parameters.AddWithValue("@id",txt1.Text);
   cmd.Parameters.AddWithValue("@id",TextBox1.Text);
   cmd.Parameters.AddWithValue("@id",TextBox2.Text);

   con.Open();
   cmd.ExcuteNonQuery();
   con.Close();
  lbl4.Text = "Data Saved Successfully";
}
   protected void btn2_click(object sender, EventArgs e)
            {
    var file = FileInfo(@"C:\Users\sample.xlsx");
                      ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                      using(ExcelPackage excel = new ExcelPackage(file))
                      {
                           ExcelWorksheet sheet =  excel.Workbook.Worksheets[''sheet1"];

                           SqlConnection  con = new SqlConnection(@"");
                            SqlCommand cmd = new SqlCommand("select * from tbl_students");
                             con.Open();
                             SqlDataAdapter da= new SqlDataAdapter(cmd);
                                  DataTable dt = new DataTable();
                                    da.Fill(dt);
                                       int count = dt.Rows.Count;
                                      sheet.Cells.LoadDataFromDataTable(dt,true);
                                           
                                        FileInfo xfile =  new FileInfo(@"C:\Users\sample.xlsx");
                                    excel.SaveAs(xfile);
                            }
                
                         }
}

//UIexcel.aspx


//UIexcel.aspx

Sunday, 14 June 2020

C# Code for Move Data from Database to excel

 C# Code for Move the Data from Database Table to Excel Sheet

Asp.Net provides a service Move the data from Database table to Excel sheet by using C# code, Create a Table in Database with Sql server and write C# code for move the data by creating console application in Microsoft Visual studio IDE.Need to install the nuget package  from the manage Nuget package.

in sql create table as tbl_students in Database

Goto solution explorer->right click on the project->select Mange Nuget Package

//Program.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using OfficeOpenXml;

namaspace Movedatatoexcelfile
{
     class Program
       {
           static void Main(string[] args)
                   {
            
                         var file = FileInfo(@"C:\Users\sample.xlsx");
                      ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                      using(ExcelPackage excel = new ExcelPackage(file))
                      {
                           ExcelWorksheet sheet =  excel.Workbook.Worksheets[''sheet1"];

                           SqlConnection  con = new SqlConnection(@"");
                            SqlCommand cmd = new SqlCommand("select * from tbl_students");
                             con.Open();
                             SqlDataAdapter da= new SqlDataAdapter(cmd);
                                  DataTable dt = new DataTable();
                                    da.Fill(dt);
                                       int count = dt.Rows.Count;
                                      sheet.Cells.LoadDataFromDataTable(dt,true);
                                           
                                        FileInfo xfile =  new FileInfo(@"C:\Users\sample.xlsx");
                                    excel.SaveAs(xfile);
                            }
                
                         }
     
                    }
                
                       

Saturday, 13 June 2020

ASP.NET Download Button

ASP.NET Download Button Code in Asp.net

ASP.NET provides implicit object Response and its methods to download file from the server. We can use these methods in our application to add a feature of downloading file from the server to the local machine.

Here, we are creating an example that allows us to download file.


// Webform1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DownloadButton.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <title></title>
</head>
<body style="background-color:#eeeeee;">
    <form id="form1" runat="server" class="form-group" style="background-color:#ffffff; width:500px; height:auto; margin:50px auto 10px auto; padding:30px; border-radius:8px; overflow:hidden;box-shadow:0 2px 10px -3px #333;">
        <div align="center" >
            <p style="text-decoration-style:solid">Download the latest CORONAVIRUS status</p>
            <asp:Button ID="Button1" runat="server"  Text="Download"  Class="form-control;btn btn-success" OnClick="Button1_Click" />
        </div>
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </form>
</body>
</html>


// Webform1.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DownloadButton
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            
            try
            {
                Response.ContentType = "Application/octect-stream";
                Response.AppendHeader("Content-Disposition", "attachment; filename=Coronalive.xlsx");
                Response.TransmitFile(Server.MapPath("~/Files/CoronaLive.xlsx"));
                Response.End();
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
            
           
            }
    }
}

// Design:-