Search code examples
c#.nettextwriter

TextWriter: Need to fetch data from DB to excel


I am working on requirement to read data from DB(from an array(String[] getPersons) as input) and write it to excel file. I struck with one scenario where in DB, I am having DepartmentID value as 1,2,3 e.t.c. Where 1 is for CSE,2 for ECE,3 for IT e.t.c. Now, the below code is fetching the numbers for DepartmentId and instead i need to have respective departments for the numbers.


var container = db.GetContainer(containerId);
var q = container.GetItemLinqQueryable<Student>();
var requests = q.Where(p => getStudents.Contains(p.StudentName)).ToFeedIterator();

using (var ms = new MemoryStream())
  {
TextWriter tw = new StreamWriter(ms);
 foreach (var request in requests)
                {
                    tw.WriteLine($"{request.DepartmentId},{request.StudentName}");

                }
                tw.Flush();           
                await ms.CopyToAsync(response.FileContent).ConfigureAwait(false);
   }

Please note that, There is no field in DB for DepartmentName(which cannot be added as well) and i need to somehow convert DepartmentId to respective DepartmentNames and then write it to excel. Is there a way to do that? I am open to suggestions. Thanks in Advance!!!


Solution

  • If you have all departments you could always hardcode them if they are not available in another way.

    Create a method for translation:

        private static string GetDepartmentName(int id)
        {
            switch(id)
            {
                case 1:
                    return "CSE";
                case 2:
                    return "ECE";
                case 3:
                    return "IT";
                default:
                    throw new NotImplementedException("No such id!");
            }
        }
    

    Then you can use that in your code:

            using (var ms = new MemoryStream())
            {
                TextWriter tw = new StreamWriter(ms);
                foreach (var request in requests)
                {
                    tw.WriteLine($"{GetDepartmentName(request.DepartmentId)},{request.StudentName}");
    
                }
                tw.Flush();
                await ms.CopyToAsync(response.FileContent).ConfigureAwait(false);
            }
    

    Then just add all the other departments in the "GetDepartmentName" method.

    Hope this works, and if not then please let me know what I missed.