Export an Excel (XLSX) From a Data Set

Sometimes, we have situations where we get data into a data set from the database and have to export the data in an Excel sheet.

If we have to export a DataTable's data, we will simply export it into an Excel sheet as a single sheet, but for a data set, we have to loop through the number of tables and each table will create a new sheet. It will add a new sheet to Excel. 

Below is the code to export the data set's data into an Excel sheet (.XLSX format). 
  1. public void ExportToExcelDataset(DataSet ds) {  
  2.   
  3.  int TableCount = ds.Tables.Count;  
  4.  using(XLWorkbook wb = new XLWorkbook()) {  
  5.   for (int i = 0; i < TableCount; i++) {  
  6.    try {  
  7.     DataTable dt = ds.Tables[i];  
  8.     string[] columnNames = (from dc in dt.Columns.Cast < DataColumn > () select dc.ColumnName).ToArray();  
  9.     // int Cell = 0;  
  10.   
  11.     int count = columnNames.Length;  
  12.     object[] array = new object[count];  
  13.     dt.Rows.Add(array);  
  14.     wb.Worksheets.Add(dt, ds.Tables[i].TableName);  
  15.   
  16.   
  17.   
  18.    } catch (Exception ex) {  
  19.     objException = new BusinessLogicLayer.ExceptionHelper();  
  20.     // call the LogErrorToDB() method to save the error log into ErrorLog table.  
  21.     objException.LogErrorToDB(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace), Convert.ToString(ex.Source), Convert.ToString(ex.TargetSite), System.DateTime.Now);  
  22.    } finally {  
  23.   
  24.    }  
  25.   }  
  26.   string ReportName = "attachment; filename=ModificationLogReport_" + DateTime.Now.ToString() + ".xlsx";  
  27.   Response.Clear();  
  28.   Response.Buffer = true;  
  29.   Response.Charset = "";  
  30.   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
  31.   Response.AddHeader("content-disposition", ReportName);  
  32.   using(MemoryStream MyMemoryStream = new MemoryStream()) {  
  33.    wb.SaveAs(MyMemoryStream);  
  34.    MyMemoryStream.WriteTo(Response.OutputStream);  
  35.    Response.Flush();  
  36.    Response.End();  
  37.   }  
  38.  }  
  39. }   

It will add Excel columns of each sheet by checking the column count of each table of the data set.

For Microsoft 365 .XLSX, we use the line given below as content type.

  1. Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";   

  1. wb.Worksheets.Add(dt, ds.Tables[i].TableName); //This line will add the sheet with data and give it table Name  

After adding all the sheets in the Workbook, as per the tables in the database, it will save the Excel sheet in the memory stream from where it will present an output.

Next Recommended Reading Export DataGridView Data To Excel In C#