Thursday, 28 December 2017

Excel Manipulation

protected void LoadDatatoControlFile(Int32 BatchId)
        {
            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Function 'LoadDatatoControlFile(BatchId)' Call Started");
            try
            {
                bool IsValidateDataCheck = false;
                if (hdnDataType.Value == "2")
                {
                    IsValidateDataCheck = true;
                }

                ArrayList DT1 = new ArrayList();
                string StrFilename = "";
                string Uploadedfiletype = "";
                string StrConn = string.Empty;
                /**** Checking if file is selectd to upload ****/
                if (IsValidateDataCheck)
                {
                    if (FileUpload3.HasFile)
                    {
                        StrFilename = System.IO.Path.GetFileName(FileUpload3.PostedFile.FileName.ToString());
                    }
                }
                else
                {
                    if (FileUpload1.HasFile)
                    {
                        StrFilename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
                    }
                }

                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - control file name uploaded is - " + StrFilename);

                string[] Files = Directory.GetFiles(Server.MapPath(""));
                foreach (string file in Files)
                {
                    int Length = file.Length;
                    int LastIndex = file.LastIndexOf('\\');

                    string ArFile = "";
                    ArFile = file.Substring(LastIndex + 1, (Length - LastIndex - 1));

                    if (ArFile.ToLower().Contains(".xls"))
                    {
                        //if (ArFile == strFilename)
                        //{
                        File.Delete(file);
                        //}
                    }
                }

                /*****  Including the connection string for the EXCEL file containing the filename and Provider settings. ****/
                StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(StrFilename) + ";Extended Properties='Excel 8.0;IMEX=1'";
                //strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(strFilename) + ";Extended Properties=Excel 12.0 Xml;";
                /***** Create a new connection object. ****/
                OleDbConnection ObjCSVCon = new OleDbConnection(StrConn);
                /****** Create a DataTable which will store spread sheet names. *****/
                DataTable dtsn = null;
                /****** This is to read Uploaded file type. *****/
                string FileExt = "";
                if (IsValidateDataCheck)
                {
                    Uploadedfiletype = FileUpload3.PostedFile.ContentType.ToString().ToLower();
                    FileExt = System.IO.Path.GetExtension(FileUpload3.PostedFile.FileName.ToString());
                }
                else
                {
                    Uploadedfiletype = FileUpload1.PostedFile.ContentType.ToString().ToLower();
                    /****** Checking if Uploaded file type is Excel or not. *****/
                    ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Uploaded control file type - " + Uploadedfiletype);
                    FileExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName.ToString());
                }

                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Uploaded control file Extension - " + FileExt);

                if (Uploadedfiletype != "application/excel" && Uploadedfiletype != "application/vnd.ms-excel" && Uploadedfiletype != "application/octet-stream" && Uploadedfiletype != "application/ms-excel")
                {
                    ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Uploaded control file type is not in 'application/excel','application/vnd.ms-excel','application/octet-stream','application/ms-excel' - " + Uploadedfiletype);
                    /****** If Uploaded file type is not Excel show error message. *****/
                    if (IsValidateDataCheck)
                    {
                        lblFormatMsg2.Visible = true;
                        lblFormatMsg2.Text = "Please Upload Excel File !!!";
                    }
                    else
                    {
                        lblFormatMsg.Visible = true;
                        lblFormatMsg.Text = "Please Upload Excel File !!!";
                    }
                }
                else
                {
                    if (FileExt != ".xls")
                    {
                        ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Uploaded control file Extension().xls is not valid - " + FileExt);

                        /****** If Uploaded file type is not Excel show error message. *****/
                        if (IsValidateDataCheck)
                        {
                            lblFormatMsg2.Visible = true;
                            lblFormatMsg2.Text = "Please Upload Excel File !!!";
                        }
                        else
                        {
                            lblFormatMsg.Visible = true;
                            lblFormatMsg.Text = "Please Upload Excel File !!!";
                        }
                    }
                    else
                    {
                        bool Checkifhasfile = false;
                        if (IsValidateDataCheck)
                        {
                            if (FileUpload3.PostedFile.ContentLength != 0)
                            {
                                Checkifhasfile = true;
                                FileUpload3.PostedFile.SaveAs(Server.MapPath(StrFilename));
                                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - FileUpload1.PostedFile.ContentLength - " + Convert.ToString(FileUpload3.PostedFile.ContentLength));
                            }
                        }
                        else
                        {
                            if (FileUpload1.PostedFile.ContentLength != 0)
                            {
                                Checkifhasfile = true;
                                FileUpload1.PostedFile.SaveAs(Server.MapPath(StrFilename));
                                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - FileUpload1.PostedFile.ContentLength - " + Convert.ToString(FileUpload1.PostedFile.ContentLength));
                            }
                        }
                        if (Checkifhasfile)
                        {

                            //string xlFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + strFilename;                         

                            /***** Saving the Uploaded file to project folder structure to read data from spread sheets *****/
                            // FileUpload1.PostedFile.SaveAs(xlFilePath);


                            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Trying to open the connection - objCSVCon.Open()");
                            /***** Open connection for processing. ****/
                            ObjCSVCon.Open();

                            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Connection Opened - objCSVCon.Open()");

                            //This Block is to Read Sheet Names from Excel File Uploaded
                            dtsn = ObjCSVCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                            DataSet DsLabInfo = new DataSet();
                            DataLoaderBO ObjValidatBatchBO = new DataLoaderBO();
                            foreach (DataRow row in dtsn.Rows)
                            {

                                string Sql = "SELECT * FROM [" + row["TABLE_NAME"].ToString() + "]";
                                OleDbCommand ObjCmdSelect1 = new OleDbCommand(Sql, ObjCSVCon);
                                /******  Create new OleDbDataAdapter  ****/
                                OleDbDataAdapter DaCSV1 = new OleDbDataAdapter();
                                DaCSV1.SelectCommand = ObjCmdSelect1;
                                /****** Create a DataTable which will hold the data extracted from the worksheet. *****/
                                DataTable DtCSV1 = new DataTable();
                                DtCSV1.TableName = row["TABLE_NAME"].ToString().Replace("$", "");
                                /***** Fill the DataTable from the data extracted from the worksheet. ******/
                                DaCSV1.Fill(DtCSV1);
                                DaCSV1 = null;
                                if (DtCSV1.TableName.ToLower() == "metadata")
                                {
                                    ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Calling function 'ValidateControlFile(dtCSV1, BatchId)'");
                                    try
                                    {
                                        ValidateControlFile(DtCSV1, BatchId);
                                    }
                                    catch (Exception ex)
                                    {
                                        ObjLogger.WriteExceptionLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile - ValidateControlFile", ex, HttpContext.Current);
                                    }
                                    ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - Completed with function calling 'ValidateControlFile(dtCSV1, BatchId)' successfully");
                                }
                            }
                            ObjCSVCon.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Exception in function 'LoadDatatoControlFile'");
                ObjLogger.WriteExceptionLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", ex, HttpContext.Current);
            }
        }

        protected void LoadDatatoDatafileCSV(Int32 BatchId)
        {
            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - trying to call function 'LoadDatatoDatafileCSV(BatchId)' - started ");
            try
            {

                bool IsValidateDataCheck = false;
                if (hdnDataType.Value == "2")
                {
                    IsValidateDataCheck = true;
                }

                string[] Files = Directory.GetFiles(Server.MapPath("UploadedCSVFiles"));
                foreach (string file in Files)
                    File.Delete(file);

                string StrFilename = "";
                string Uploadedfiletype = "";

                bool Checkifhasfile = false;
                if (IsValidateDataCheck)
                {
                    if (FileUpload4.HasFile)
                    {
                        Checkifhasfile = true;
                        /******** Reading uploaded file name ********/
                        StrFilename = System.IO.Path.GetFileName(FileUpload4.PostedFile.FileName.ToString());
                    }
                }
                else
                {
                    if (FileUpload2.HasFile)
                    {
                        Checkifhasfile = true;
                        /******** Reading uploaded file name ********/
                        StrFilename = System.IO.Path.GetFileName(FileUpload2.PostedFile.FileName.ToString());
                    }
                }
                if (Checkifhasfile)
                {
                    string FileExt = "";
                    FileInfo FileInfo;
                    if (IsValidateDataCheck)
                    {
                        FileInfo = new FileInfo(FileUpload4.PostedFile.FileName);
                        Uploadedfiletype = FileUpload4.PostedFile.ContentType.ToString().ToLower();
                        FileExt = System.IO.Path.GetExtension(FileUpload4.PostedFile.FileName.ToString());
                    }
                    else
                    {
                        FileInfo = new FileInfo(FileUpload2.PostedFile.FileName);
                        Uploadedfiletype = FileUpload2.PostedFile.ContentType.ToString().ToLower();
                        FileExt = System.IO.Path.GetExtension(FileUpload2.PostedFile.FileName.ToString());
                    }
                    if (FileExt.ToLower() == ".csv")
                    {
                        string FileName = FileInfo.Name.Replace(".csv", "").ToString();
                        string CsvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + FileInfo.Name;
                        //Save the CSV file in the Server inside 'MyCSVFolder'
                        if (IsValidateDataCheck)
                        {
                            FileUpload4.SaveAs(CsvFilePath);
                        }
                        else
                        {
                            FileUpload2.SaveAs(CsvFilePath);
                        }

                        //Fetch the location of CSV file
                        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=NO;FMT=Delimited;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
                        // load the data from CSV to DataTable
                        OleDbDataAdapter Adapter = new OleDbDataAdapter(StrSql, StrCSVConnString);
                        DataTable DtCSV = new DataTable();
                        DataTable DtSchema = new DataTable();
                        Adapter.FillSchema(DtCSV, SchemaType.Mapped);
                        Adapter.Fill(DtCSV);
                        if (DtCSV.Rows.Count > 0)
                        {
                            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - trying to call function 'ValidateDataFileData(dtCSV, BatchId)' ");
                            try
                            {
                                NewValidateDataFileData(DtCSV, BatchId);
                            }
                            catch (Exception ex)
                            {
                                ObjLogger.WriteExceptionLog("DataLoaderNew.ascx.cs", "LoadDatatoDatafileCSV - ValidateDataFileData", ex, HttpContext.Current);
                            }
                            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoControlFile", "Uploading Control N Data Files - trying to call function 'ValidateDataFileData(dtCSV, BatchId)' completed successfully");
                        }
                        else
                        {
                            if (IsValidateDataCheck)
                            {
                                lblFormatMsg2.Visible = true;
                                lblFormatMsg2.Text = "Data Inconsistency Error";
                            }
                            else
                            {
                                lblFormatMsg.Visible = true;
                                lblFormatMsg.Text = "Data Inconsistency Error";
                            }
                        }

                        string[] Files1 = Directory.GetFiles(Server.MapPath("UploadedCSVFiles"));
                        foreach (string file in Files1)
                            File.Delete(file);


                    }
                    else
                    {
                        if (IsValidateDataCheck)
                        {
                            lblFormatMsg2.Text = "Please Upload Csv File !!!";
                            lblFormatMsg2.Visible = true;
                        }
                        else
                        {
                            lblFormatMsg.Text = "Please Upload Csv File !!!";
                            lblFormatMsg.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoDatafileCSV", "Exception in function 'LoadDatatoControlFile'");
                ObjLogger.WriteExceptionLog("DataLoaderNew.ascx.cs", "LoadDatatoDatafileCSV", ex, HttpContext.Current);
            }
        }

        protected void LoadDatatoDataFile(Int32 BatchId)
        {
            ObjLogger.WriteLog("DataLoaderNew.ascx.cs", "LoadDatatoDataFile", (HttpContext.Current).ToString());

            try
            {

                ArrayList DT1 = new ArrayList();
                string StrFilename = "";
                string Uploadedfiletype = "";
                string StrConn = string.Empty;
                /**** Checking if file is selectd to upload ****/
                if (FileUpload2.HasFile)
                {
                    /******** Reading uploaded file name ********/
                    StrFilename = System.IO.Path.GetFileName(FileUpload2.PostedFile.FileName.ToString());
                }

                /*****  Including the connection string for the EXCEL file containing the filename and Provider settings. ****/
                StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(StrFilename) + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
                /***** Create a new connection object. ****/
                OleDbConnection ObjCSVCon = new OleDbConnection(StrConn);
                /****** Create a DataTable which will store spread sheet names. *****/
                DataTable Dtsn = null;
                /****** This is to read Uploaded file type. *****/
                Uploadedfiletype = FileUpload2.PostedFile.ContentType.ToString().ToLower();
                /****** Checking if Uploaded file type is Excel or not. *****/
                if (Uploadedfiletype != "application/excel" && Uploadedfiletype != "application/vnd.ms-excel" && Uploadedfiletype != "application/octet-stream" && Uploadedfiletype != "application/ms-excel")
                {
                    /****** If Uploaded file type is not Excel show error message. *****/
                    //lblMsg.Visible = true;
                    //lblMsg.CssClass = "redtext";
                    //lblMsg.Text = "Please Upload Excel File !!!";
                }
                else
                {
                    if (FileUpload2.PostedFile.ContentLength != 0)
                    {
                        /***** Saving the Uploaded file to project folder structure to read data from spread sheets *****/
                        FileUpload2.PostedFile.SaveAs(Server.MapPath(StrFilename));
                        /***** Open connection for processing. ****/
                        ObjCSVCon.Open();

                        //This Block is to Read Sheet Names from Excel File Uploaded
                        Dtsn = ObjCSVCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        DataSet DsLabInfo = new DataSet();
                        DataLoaderBO ObjValidatBatchBO = new DataLoaderBO();
                        foreach (DataRow row in Dtsn.Rows)
                        {

                            string Sql = "SELECT * FROM [" + row["TABLE_NAME"].ToString() + "]";
                            OleDbCommand ObjCmdSelect1 = new OleDbCommand(Sql, ObjCSVCon);
                            /******  Create new OleDbDataAdapter  ****/
                            OleDbDataAdapter daCSV1 = new OleDbDataAdapter();
                            daCSV1.SelectCommand = ObjCmdSelect1;
                            /****** Create a DataTable which will hold the data extracted from the worksheet. *****/
                            DataTable DtCSV1 = new DataTable();
                            DtCSV1.TableName = row["TABLE_NAME"].ToString().Replace("$", "");
                            /***** Fill the DataTable from the data extracted from the worksheet. ******/
                            daCSV1.Fill(DtCSV1);
                            daCSV1 = null;

                            if (DtCSV1.TableName.ToLower() == "template")
                            {
                                ValidateDataFileData(DtCSV1, BatchId);

                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                ObjLogger.WriteExceptionLog("DataLoaderNew.ascx.cs", "LoadDatatoDataFile", ex, HttpContext.Current);
            }
        }

No comments:

Post a Comment