Click here to Skip to main content
16,008,750 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have 4 columns and 3000 rows in my excel sheet. I need to read data like Row1col1 , Row1Col2 , Row1Col3 and Row1Col4. After reading the name from Row1Col1 , i need to fetch its id from oracle table. Similarly then read Row1Col2 and fetch its Id from oracle table and so on till Row1Col4. After getting all the Id's of all the columns of the first row , i need to check in one of the oracle table for that match exists or not. If that match exists then leave it else insert that record. For doing so, Currently i am using Microsoft.Office.Interop.Excel to read excel data row by row. Currently it is taking around 20 minutes to read 3508 records that is too long. I am wondering if this is the best way to do it or if there are better / more efficent ways (or just more intelligent ways - Maybe Linq / native .Net providers) to use instead?
Any help would be veru appreciated.

What I have tried:

[HttpPost]
C#
public ActionResult ReadExcel(HttpPostedFileBase excelFile)
{
    TempData["SuccessMsg"] = "";
    int count = 0;
    int rowCount = 0;
    bool writesFilename = false;
    if (excelFile == null || excelFile.ContentLength == 0)
    {
        TempData["ErrorMsg"] = "Please select File";
        return View("UploadData");
    }
    else
    {

        if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
        {
            string fileName = excelFile.FileName;
            string extension = Path.GetExtension(Request.Files["excelFile"].FileName);
            string path = Server.MapPath("~/Content/" + excelFile.FileName);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            excelFile.SaveAs(path);

            var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            var fullFileName = Path.Combine(desktopFolder, fileName + ".txt");
            if (System.IO.File.Exists(fullFileName))
            {
                System.IO.File.Delete(fullFileName);
            }

            MyExcel.Application xlApp;
            MyExcel.Workbook xlWorkBook;
            MyExcel.Worksheet xlWorkSheet;
            MyExcel.Range range;

            string ExcelAgencyName, ExcelAgencyGroupName, ExcelSource, ExcelFunctionalArea;
            decimal AgencyKey;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new MyExcel.Application();
            xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (MyExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            rowCount = range.Rows.Count - 1;

            //Parallel.ForEach(xlWorkSheet.Rows.Cast<MyExcel.Range>(), currentRow =>
            //{
                for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++)
                {
                    for (cCnt = 1; cCnt <= range.Columns.Count; cCnt += 5)
                    {
                        decimal dbAgencyGroupKey = 0;
                        decimal dbSourceKey;
                        decimal dbFunctionalKey;


                        BarcDataContext bc = new BarcDataContext();
                        ExcelAgencyName = (range.Cells[rCnt, cCnt] as MyExcel.Range).Text.ToString();
                        ExcelAgencyGroupName = (range.Cells[rCnt, cCnt + 1] as MyExcel.Range).Text.ToString();
                        ExcelSource = (range.Cells[rCnt, cCnt + 2] as MyExcel.Range).Text.ToString();
                        ExcelFunctionalArea = (range.Cells[rCnt, cCnt + 3] as MyExcel.Range).Text.ToString();

                        dbSourceKey = bc.REF_SRC_SUB_AREA.Where(m => m.SRC_SUB_AREA == ExcelSource.Trim()).FirstOrDefault().SRC_SUB_KEY;
                        dbFunctionalKey = bc.REF_SRC_FUNC_AREA.Where(m => m.SRC_FUNC_AREA == ExcelFunctionalArea.Trim()).FirstOrDefault().SRC_FUNC_KEY;


                        DIM_AGENCY objAgencyKey = bc.DIM_AGENCY.Where(m => m.AGENCY_NAME.ToUpper() == ExcelAgencyName.ToUpper() && m.SRC_SUB_KEY == dbSourceKey).FirstOrDefault();

                        if (objAgencyKey != null && dbFunctionalKey != 0)
                        {
                            AgencyKey = objAgencyKey.AGENCY_KEY;
                        }
                        else
                        {
                            StreamWriter sw = null;
                            sw = new StreamWriter(fullFileName, true);
                            sw.WriteLine(ExcelAgencyName);
                            sw.Close();
                            writesFilename = true;
                            break;
                        }

                        DIM_AGENCY_GROUP objAgencyGroup = bc.DIM_AGENCY_GROUP.Where(m => m.AGENCY_GROUP_NAME.ToUpper() == ExcelAgencyGroupName.ToUpper() && m.SRC_FUNC_KEY == dbFunctionalKey).FirstOrDefault();

                        if (objAgencyGroup != null)
                        {
                            dbAgencyGroupKey = objAgencyGroup.AGENCY_GROUP_KEY;
                        }

                        if (dbAgencyGroupKey == 0)
                        {
                            decimal agencyGrpKey = AgencyGroupRepository.InsertAgencyGroup(ExcelAgencyGroupName, dbFunctionalKey);
                            if (agencyGrpKey != 0)
                            {
                                XREF_AGENCY_TAGGING objXrefTagging = bc.XREF_AGENCY_TAGGING.Where(m => m.AGENCY_KEY == AgencyKey && m.SRC_FUNC_KEY == dbFunctionalKey).FirstOrDefault();
                                if (objXrefTagging != null)
                                {
                                    if (objXrefTagging.AGENCY_GROUP_KEY == agencyGrpKey)
                                    {

                                    }
                                    else
                                    {
                                        decimal agencyTaggingSrNo = AgencyGroupRepository.UpdateTaggingAgencyAgencyGroup(AgencyKey, agencyGrpKey, dbFunctionalKey);
                                        count = count + 1;
                                    }
                                }
                                else
                                {
                                    decimal agencyTaggingSrNo = AgencyGroupRepository.TagAgencyAgencyGroup(AgencyKey, agencyGrpKey, dbFunctionalKey);
                                    count = count + 1;
                                }

                            }
                        }
                        else
                        {

                            XREF_AGENCY_TAGGING objXrefTagging = bc.XREF_AGENCY_TAGGING.Where(m => m.AGENCY_KEY == AgencyKey && m.SRC_FUNC_KEY == dbFunctionalKey).FirstOrDefault();
                            if (objXrefTagging != null)
                            {
                                if (objXrefTagging.AGENCY_GROUP_KEY == dbAgencyGroupKey)
                                {

                                }
                                else
                                {
                                    decimal agencyTaggingSrNo = AgencyGroupRepository.UpdateTaggingAgencyAgencyGroup(AgencyKey, dbAgencyGroupKey, dbFunctionalKey);
                                    count = count + 1;
                                }


                            }
                            else
                            {
                                decimal agencyTaggingSrNo = AgencyGroupRepository.TagAgencyAgencyGroup(AgencyKey, dbAgencyGroupKey, dbFunctionalKey);
                                count = count + 1;
                            }

                        }
                    }
                }
            //});
        }
        else
        {
            TempData["ErrorMsg"] = "Invalid file type. Upload only xlx or xlsx file type.";
            return View("UploadData");
        }

    }

    int totalCount = rowCount - count;

    if (writesFilename == true && count > 0)
    {
        TempData["SuccessMsg"] = "Out of" + " " + rowCount + " " + "," + " " + totalCount + " " + "Agency names not found in database. Please view the text file saved on your desktop to get the agency names.";
    }
    else if (count == 0 && writesFilename == true)
    {
        TempData["ErrorMsg"] = "None of the agency names found in database. Please view the text file saved on your desktop to get the agency names.";
    }
    else if (count > 0 && writesFilename == false)
    {
        TempData["ErrorMsg"] = "Out of" + " " + rowCount + " " + "," + " " + totalCount + " " + "Agency group keys got updated.";
    }
    return View("UploadData");
}
Posted
Updated 4-Jul-16 2:15am
v5
Comments
Kornfeld Eliyahu Peter 4-Jul-16 5:58am    
Use OLE DB driver for Excel and handle your worksheets as tables...
Laysence 5-Sep-16 7:42am    
You could also use an excel library for C# which has a much better performances then usage of excel interop in C#, you can find the comparions sheet here.

To read excel data


C#
string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}


Source
.net - How to read data from excel file using c# - Stack Overflow[^]
 
Share this answer
 
Comments
Member 10398113 4-Jul-16 7:51am    
But this way it can read column wise data and i want to read the data like first row all the columns then 2nd row and its all the columns one by one
raju melveetilpurayil 4-Jul-16 8:34am    
have a look on this please http://stackoverflow.com/questions/17577184/importing-excel-into-a-datatable-quickly
Member 10398113 5-Jul-16 0:31am    
Thanks for your response Raju sir. Here my only challenge is not only to read the excel data and put it into data table or data set but also after reading the column values i have to access oracle data base and do stuff. If you read my question and go through with my code you will understand what exactly my requirement is. Can you please give me the efficient code for the same which fulfill my requirement. Thanks in advance sir.
This is not just reading an Excel file, you also access a data base and do stuff.

First thing to do is to run a profiler to see how much time it takes for each part of the program. The part that take the most time is probably where you can gain the most.
Dividing by 2 the time it takes for a part that only take 10% of the whole will only save 5%.
Saving 2/3 of a part that take 75% is saving 50% of the whole.

You need to know which operation takes time before teaking you code.

Profiling (computer programming) - Wikipedia, the free encyclopedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900