Home > Software design >  c# - Export large object data to Excel file
c# - Export large object data to Excel file

Time:04-15

my program gather data from different XML files by selecting data with LINQ. It results having below proprieties for each element of my object collections. Each collection having arround 10k objects (with 11 proprieties), 15 collection.

https://i.stack.imgur.com/5R1Hj.jpg

Everything's fine until i need to export them to excel file. I'm looping each cell data as below, then this is far too long. As describe above, there is large data to export.

            foreach (dataContainer elt in Liste) 
        {
            
            for(int b = 1; b <= 11; b  ) 
            { 
            Excel.Range currentRange = outputWorksheet.Cells[Liste.IndexOf(elt) 2, b];
                switch (b)
                {
                    case 1: currentRange.Value2 = elt.ctNumber;break;
                    case 2: currentRange.Value2 = elt.isoType; break;
                    case 3: currentRange.Value2 = elt.bkgNumber; break;
                    case 4: currentRange.Value2 = elt.POO; break;
                    case 5: currentRange.Value2 = elt.POL; break;
                    case 6: currentRange.Value2 = elt.POD; break;
                    case 7: currentRange.Value2 = elt.OPE; break;
                    case 8: currentRange.Value2 = elt.Empty; break;
                    case 9: currentRange.Value2 = elt.flagOOG; break;
                    case 10: currentRange.Value2 = elt.teus; break;
                    case 11: currentRange.Value2 = elt.weight; break;
                }
            }
        }

How can i improve my way to export data in excel ? Knowing i can't use .csv file.

CodePudding user response:

If you are creating a standalone Excel file instead of updating the one currently being displayed, directly creating the file using Open XML SDK rather than Excel Object Model would be faster - start at https://docs.microsoft.com/en-us/office/open-xml/spreadsheets

CodePudding user response:

After few research, i found out the best way to proceed for my case, very quick method. I create a an object that will contains my 2D data, then assign an excel range value = to this object.

object[,] virtualCells = new object[Liste.Count, propertyOfContainer.Length];
        for(int j = 0; j < Liste.Count; j  )
        {
            for(int h = 0; h < 12; h  )
            {
                virtualCells[j, h] = Liste[j].GetType().GetProperty(propertyOfContainer[h]).GetValue(Liste[j]);
            }
        }
        
        int lastRow;
        if (String.IsNullOrEmpty(outputWorksheet.Range["L2"].Value2)) { lastRow = 1; }
        else { lastRow = outputWorksheet.Range["L1"].End[Excel.XlDirection.xlDown].Row; }

outputWorksheet.Range[outputWorksheet.Cells[lastRow 1, 1],outputWorksheet.Cells[lastRow   Liste.Count, propertyOfContainer.Length]].Value2 = virtualCells;
  • Related