Search code examples
c#excelasp.net-mvc-5export-to-excelclosedxml

How to assign a list to a Cell(Dropdown format) in closedXML while Exporting to Excel


I am just trying to Export a Datatable (Datatable doesn't have any data - having only header). In addition, i have a List<String> which i want to append to the column, such that, after export to excel that column (all cells except header) should contain list data as Dropdown format.

I have googled a lot and couldn't able to find any solutions. Below are the links which i have visited but no luck.

StackOverflow

Codeplex - ClosedXML

And below are the one what i have tried so far.

    private void ExcelExport(DataTable dt, GridView Template)
    {
        bool isListRequired = false;
        List<string> groupCodeList = new List<string>(); ;
        Template.DataBind();
        if (Template.HeaderRow != null)
        {
            foreach (TableCell cell in Template.HeaderRow.Cells)
            {
                if (cell.Text == "ActivityGroup_Code")
                {
                    isListRequired = true;
                    groupCodeList = db.PMS_M_ActivityGroup.Select(a => a.ActivityGroup_Code).ToList();
                }
                    dt.Columns.Add(cell.Text);
            }

            var workbook = new XLWorkbook();
            var returnValue = workbook.AddWorksheet(dt);
            var worksheet = workbook.Worksheet(1);
            if (isListRequired)
            {
                //worksheet.Cell("E2").DataValidation.List(string.Join("",groupCodeList.ToArray()));
                //worksheet.Cell(2,5).InsertData(groupCodeList);

                // Trying to add a list to the Cell (E2) - and applying datavalidation to the Column (5th column - E Range)
                // Dropdown is created in excel(with blank) but data is not population to that dropdown
                worksheet.Cell(2, 5).InsertData(groupCodeList);
                worksheet.Column(5).SetDataValidation().List(string.Join("", groupCodeList.ToArray()));
            }

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=ExcelFormat.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.Charset = "";
            using (MemoryStream MyMemoryStream = new MemoryStream())
            {
                workbook.SaveAs(MyMemoryStream);
                MyMemoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
        }
    }

And the code where i am calling this method is

 List<PMS_M_ActivityGroup> activitygroup = new List<PMS_M_ActivityGroup>();
 activitygroup = db.PMS_M_ActivityGroup.Select(a => a).ToList();
 DataTable dt2 = new DataTable("Excel Template");
 GridView Template2 = new GridView();
 Template2.DataSource = activitygroup;
 ExcelExport(dt2, Template2);

Request you to provide me the solution how to achieve the required functionality.

Thank you


Solution

  • I got the solution. It's not that much simple but we need to do few tricks to achieve this functionality. Posting here - might be helpful for other developers who are using specifically ClosedXML library.

    So what we need to do is : we need to create a separate(Second) sheet, apply DataValidation to the 1st sheet column where dropdown to be appeared.

    private void ExcelExportValidation(DataTable dt, GridView Template)
    {
        try
        {
            bool isListRequired = false;
            List<string> groupCodeList = new List<string>(); ;
            Template.DataBind();
            if (Template.HeaderRow != null)
            {
               foreach (TableCell cell in Template.HeaderRow.Cells)
               {
                   if (cell.Text == "ActivityGroup_Code")
                   {
                       isListRequired = true;
                       groupCodeList = db.PMS_M_ActivityGroup.Select(a => a.ActivityGroup_Code).ToList();
                   }
                   dt.Columns.Add(cell.Text);
               }
    
               var workbook = new XLWorkbook();
               var returnValue = workbook.AddWorksheet(dt);
               var worksheet = workbook.Worksheet(1);
               if (isListRequired)
               {
                   var tempDt = Helper.ConvertListToDataTable(groupCodeList);
                   tempDt.TableName = "Sheet1";
                   var returnValue2 = workbook.AddWorksheet(tempDt);
                   var worksheet2 = workbook.Worksheet(2);
                   int lastCellNo = groupCodeList.Count + 1;                       
                         worksheet.Column(5).SetDataValidation().List(worksheet2.Range("A2:A" + lastCellNo), true);                                               
                }
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=ExcelFormat.xlsx");
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.Charset = "";
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    workbook.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            ExceptionLogging.SendErrorToText(ex);
        }
    }