Creating Excel File using C#

By using ClosedXML we can create excel file.

Step 1 - Download and Add the DLL from Codeplex.

Codeplex Link - https://closedxml.codeplex.com/ 

Example - 1
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");

Example -2 : Reading from Data table to Excel
 private static void generateXLSX(DataTable dt, string csvPath)
        {
            FileStream fs = new FileStream(csvPath, FileMode.Create, FileAccess.ReadWrite);
            var workbook = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add(dt, "User Information");
            try
            {
                workbook.SaveAs(fs);
                fs.Close();
            }
            catch (Exception exc)
            {
            }
        }

You May Also Like

0 comments