🔍 Introduction
Excel dropdown lists are a powerful way to restrict user input to predefined options, improving accuracy and data consistency.
In this article, we’ll learn how to generate an Excel file with a dropdown list using a .NET Core Web API and the ClosedXML library. This is especially useful when you want to provide downloadable Excel templates where users can choose predefined values instead of typing them manually.
🧰 Prerequisites
Before we start, make sure you have:
.NET 6 or later installed
The ClosedXML NuGet package
dotnet add package ClosedXMLBasic understanding of ASP.NET Core Web API
🧩 Step 1: Create a Web API Endpoint
Create a new controller method in your ASP.NET Core API project.
[HttpGet("generate-excel-dropdown")]
public IActionResult GenerateExcelDropdown()
{
var ListData = "\"Option1,Option2,Option3\"";
using (var workbook = new ClosedXML.Excel.XLWorkbook())
{
var ws = workbook.AddWorksheet("Dropdown Sheet");
// Label for the dropdown cell
ws.Cell("A1").Value = "Select an option";
// Dropdown target cell
ws.Cell("B1").Value = "";
var DropDown = ws.Range("B1");
// Configure data validation
var validation = DropDown.CreateDataValidation();
validation.List(ListData, true);
validation.IgnoreBlanks = true;
validation.InCellDropdown = true;
// Return the Excel file
using (var ms = new MemoryStream())
{
workbook.SaveAs(ms);
return File(
ms.ToArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"DropdownList.xlsx"
);
}
}
}
🧠 Step 2: Understanding the Code
🔹 Defining the List Data
var ListData = "\"Option1,Option2,Option3\"";
Excel expects literal list values to be wrapped in double quotes.
The escaped quotes (\") tell Excel that it’s a literal list, not a formula or cell range.
Example
✅
"\"Yes,No,Maybe\""→ works❌
"Yes,No,Maybe"→ fails, Excel misinterprets it
🔹 Creating Workbook and Worksheet
var workbook = new XLWorkbook();
var ws = workbook.AddWorksheet("Dropdown Sheet");
XLWorkbookrepresents the Excel file.AddWorksheet()adds a sheet named Dropdown Sheet.
Join the conversation! Your thoughts help the community grow.