Question Generate excel files from a C# application

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
88
Programming Experience
Beginner
I have an application that is accepting two .csv files as input, comparing them using employee Ids and generating two output files in excel format - new employees and removed employees. I am storing the data of input .csv files in hashtables. Storing the data in the following format-

C#:
<key,Value>
<employee ID, Name*City*AccessCode*Role>

I am then comparing both hashtables and determining what employees are new and what are to be removed. I am storing the final results also in a hashtable.

Now, I am using ClosedXML to generate output excel files. I am converting the output hashtable into a datatable and then printing that datatable on the excel.

C#:
Datatable outputTable = new Datatable();
outputTable = ConvertHashtableToDatatable(NewEmployeeHashtable);

using(XLWorkbook wb = new XLWorkbook())
{
    var worksheet = wb.Worksheets.Add(outputTable,"Sheet1");
    wb.SaveAs(filepath);
}



  
private Datatable ConvertHashtableToDatatable(Hashtable NewEmployeeHashtable)
{
    Datatable table = new DataTable();
    table.Columns.Add("EmployeeID", typeof(string))
    .
    .
    .
    //adding 10 more columns
  
    foreach(DictionaryEntry entry in NewEmployeeHashtable)
    {
        string line = entry.Value.ToString();
        string[] splittedline = line.Split('*');
        DataRow row = table.NewRow();
        row["employeeId"] = splittedline[0];
        //adding 10  more values in a similar way
        table.Rows.Add(row);
    }
    return table;
    }
}

Earlier I was printing the output Hashtables in the .csv file but now the requirements have changed so I have to modify the code. The above code is working but it is a bit slow.Is there any other was to do this efficiently. I can have 4000-5000 rows in my output files.
Thank you.
 
Why do you need to convert from your Dictionary to DataTable before writing out to an Excel file?
 
Why do you need to convert from your Dictionary to DataTable before writing out to an Excel file?

Because ClosedXML accepts only datatable to print to excel.
Is there anyway that I can directly print a hashtable to excel using closedxml?
 
ClosedXML let's you access rows and cells directly. Yes, it maybe convenient to just pass in a DataTable to ClosedXML to have it convert those into cells, but if you are looking for efficiency, then every extra bit of code you do not run, and every extra allocation that you do not make is one more step towards efficiency code efficiency.

Now on the other hand, if it is developer efficiency you are looking for where you want to minimize the amount of thinking and/or typing that you need to do, then you probably have good enough code.
 
Back
Top Bottom