MaxBeauchemin
5/22/2019 - 9:27 PM

.Net Excel Export

Need to add the following Using statements and add the ExcelLibrary NuGet package

using ExcelLibrary.SpreadSheet; using System; using System.IO;

public class ExcelExporter
{
    private Workbook _workbook;

    public ExcelExporter()
    {
        _workbook = new Workbook();
        _workbook.Worksheets.Add(new Worksheet("Data"));
    }

    public void SetCell(int row, int col, string value)
    {
        var worksheet = _workbook.Worksheets[0];

        worksheet.Cells[row, col] = new Cell(value);
    }

    /// <summary>
    /// Returns the Full Path to the created file
    /// </summary>
    /// <param name="directory"></param>
    /// <returns></returns>
    public string ExportToDirectory(string directory)
    {
        //Create directory if it doesn't exist
        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);

        var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

        var fullPath = Path.Combine(directory, fileName);

        _workbook.Save(fullPath);

        return fullPath;
    }
}