Skip to main content

Importing Text File data into SQL Server database using Asp.Net(C#)

Importing Text File data into SQL Server database using Asp.Net(C#)


Here is code i implemented to import text file data into SQL server database .
.aspx page




<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ImportTEXT.aspx.cs" Inherits="ImportTEXT" Title="Import" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
            <table align="center" width="80%" class="tableStyle">
                <caption>
                    <br />
                    <tr>
                        <td align="center" colspan="2">
                            <asp:Label ID="lblHeader" runat="server" CssClass="lblHeader"
                                Text="Import"> </asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td align="center" colspan="2">
                            <asp:Label ID="lblError" runat="server" CssClass="lblText" ForeColor="Red">
                            </asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" width="40%">
                            <asp:Label ID="lblDes" runat="server" CssClass="lblText" Text="Upload TEXT File :"></asp:Label>
                        </td>
                        <td>
                            <asp:FileUpload ID="fuTextfile" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td align="center" colspan="4">
                            <asp:Button ID="btnSave" runat="server" CssClass="buttonStyle" Text="Save"
                                onclick="btnSave_Click" />                          
                        </td>
                    </tr>                  
                </caption>
            </table>
</asp:Content>


----------------------------------------------------------------------------------------------
code .cs file:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.OleDb;
using System.Text;
using System.Data.SqlClient;

public partial class ImportTEXT : System.Web.UI.Page
{
    Common objCommon = new Common();

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuTextfile.HasFile)
            {
                FileInfo fileinfo = new FileInfo(fuTextfile.PostedFile.FileName);
                if (fileinfo.Name.Contains(".txt"))
                {
                    string filename = fileinfo.Name.Replace(".txt", "").ToString();
                    string csvfilepath = ((Server.MapPath("Upload") + "\\") + fileinfo.Name);
                    fuTextfile.SaveAs(csvfilepath);
                    string filepath = (Server.MapPath("Upload") + "\\");
                    string strsql = (("SELECT * FROM [" + fileinfo.Name) + "]");
                    string strCSVConnstring = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + (filepath + (";" + "Extended Properties=\'text;HDR=YES;\'")));
                    OleDbDataAdapter da = new OleDbDataAdapter(strsql, strCSVConnstring);
                    DataTable dtCSV = new DataTable();
                    DataTable dtSchema = new DataTable();
                    da.FillSchema(dtCSV, SchemaType.Mapped);
                    da.Fill(dtCSV);
                    lblError.Text = dtCSV.Rows.Count.ToString();
                    if (dtCSV.Rows.Count > 0)
                    {
                        string fileFullPath = (filepath + fileinfo.Name);
                        LoadDataToDatabase(filename, fileFullPath, "|");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            objCommon.LogException(ex.Message);
        }
    }
    private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
    {
        string sqlQuery = String.Empty;
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat(string.Format("BULK INSERT {0} ", "tblInventory"));
        sb.AppendFormat(string.Format(" FROM \'{0}\'", fileFullPath));
        sb.AppendFormat(string.Format((" WITH (FIRSTROW = 4, FIELDTERMINATOR = \'{0}\' , ROWTERMINATOR = \'" + ("\n" + "\' )")), delimeter));
        sqlQuery = sb.ToString();

        SqlConnection con = new SqlConnection(@"Data Source=GLOBAL5;Initial Catalog=dbPractice;Integrated Security=True; Connection Timeout=10000");
        con.Open();
        SqlCommand sqlCmd = new SqlCommand(sqlQuery, con);
        sqlCmd.ExecuteNonQuery();
        con.Close();
        con.Open();
        SqlCommand cmd=new SqlCommand("SELECT COUNT(*) FROM tblInventory ", con);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        lblError.Text = i.ToString();
        lblError.Visible = true;
        con.Close();
        
    }
}

----------------------------------------------------------------------------------------------

And Text file contains :


MaterialNo |  Material Description  |  Qty   | Unit Value  |  Value
 10230       |    xyz..........!               |   2.0   |  1500.35    |   3000.70
like this
Things to remember 

  • Database table should contain same number of columns.
  • Datatype should be appropreate for column datatype according data contained  text file.
I hope this post will help you.
So enjoy it.

--
--
Regards,
Gajanan

Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.