Friday, 23 September 2011

Importing Contacts from .CSV file

ImportCSV.aspx

<asp:FileUpload ID="uploadCSV" runat="server" />&nbsp&nbsp
<asp:Button ID="btnUpload" runat="server" Text="Upload Contacts From CSV File" onclick="btnUpload_Click" />

ImportCSV.aspx.cs

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (uploadCSV.HasFile)
        {
            FileInfo fileInfo = new FileInfo(uploadCSV.PostedFile.FileName);

            if (fileInfo.Name.Contains(".csv"))
            {
                string fileName = fileInfo.Name.Replace(".csv", "").ToString();
                string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name;
                uploadCSV.SaveAs(csvFilePath);
                string filePath = Server.MapPath("UploadedCSVFiles") + "\\";
                string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
                string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";

               System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strSql, strCSVConnString);

               DataTable dtCSV = new DataTable();

               DataTable dtSchema = new DataTable();
               adapter.FillSchema(dtCSV, SchemaType.Mapped);
               adapter.Fill(dtCSV);
               }

        }
    }

Thanks Happy Coding.

No comments:

Post a Comment