ExpertXls Excel Library Blazor demo · .NET 10 and .NET 11

← All demos

C# code of the ImportCsv demo

Features/ImportCsvDemo.cs
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using ExpertXls.ExcelLib;

namespace ExcelLibraryDemos
{
    /// <summary>
    /// Imports a CSV file into a new workbook, formats the imported table, and exports a worksheet back to CSV.
    /// </summary>
    public static class ImportCsvDemo
    {
        /// <summary>The name of the generated file, without extension.</summary>
        public const string OutputName = "ImportFromCsv";

        /// <summary>
        /// Creates the workbook in the given format from Data\awemployees.csv and saves it to the output stream.
        /// </summary>
        /// <param name="format">Excel 97-2003 (.xls) or Excel 2007+ (.xlsx).</param>
        /// <param name="inputFolder">The folder that contains the Data and Images folders of the sample.</param>
        /// <param name="output">The stream that receives the workbook.</param>
        public static void CreateWorkbook(ExcelWorkbookFormat format, string inputFolder, Stream output)
        {
            ExcelWorkbook workbook = LoadEmployees(format, inputFolder);
            // workbook.LicenseKey = "your license key";
            workbook.DocumentProperties.Subject = "Import data from CSV";
            workbook.DocumentProperties.Comments = "Created with ExpertXls Excel Library for .NET";

            Image logo = Image.FromFile(Path.Combine(inputFolder, "Images", "logo.jpg"));
            try
            {
                ExcelCellStyle titleStyle = DemoLayout.AddTitleStyle(workbook);

                ExcelWorksheet worksheet = workbook.Worksheets[0];
                worksheet.Name = "Imported from CSV";
                DemoLayout.SetupPage(worksheet, logo, ExcelPageOrientation.Landscape);
                DemoLayout.WriteTitle(worksheet, "A2:N3", "Data Imported from a CSV File", titleStyle);

                // the CSV header row was imported in row 5; the used range ends with the last imported row and column
                int lastRow = worksheet.UsedRange.BottomRowIndex;
                int lastColumn = worksheet.UsedRange.RightColumnIndex;
                ExcelRange headerRange = worksheet[5, 1, 5, lastColumn];
                headerRange.RowHeightInPoints = 20;
                headerRange.Style.Font.Bold = true;
                headerRange.Style.Fill.FillType = ExcelCellFillType.SolidFill;
                headerRange.Style.Fill.SolidFillOptions.BackColor = Color.LightBlue;
                headerRange.Style.Borders.LineStyle = ExcelCellLineStyle.Thin;

                // the numbers and dates of the CSV file were imported as numbers and dates: show the dates of the
                // BirthDate, HireDate and ModifiedDate columns in the ISO format
                worksheet[6, 7, lastRow, 7].Style.Number.NumberFormatString = "yyyy-mm-dd";
                worksheet[6, 10, lastRow, 10].Style.Number.NumberFormatString = "yyyy-mm-dd";
                worksheet[6, 14, lastRow, 14].Style.Number.NumberFormatString = "yyyy-mm-dd";

                // keep the header visible when scrolling and fit the columns to the data
                worksheet["A6"].FreezePanes();
                worksheet.AutofitColumns();

                workbook.Save(output);
            }
            finally
            {
                workbook.Close();
                logo.Dispose();
            }
        }

        /// <summary>
        /// Saves the first worksheet of a workbook created by this demo to a CSV stream, with ';' as the separator.
        /// </summary>
        /// <param name="workbookFile">A workbook saved by CreateWorkbook.</param>
        /// <param name="csvOutput">The stream that receives the CSV text.</param>
        public static void ExportToCsv(string workbookFile, Stream csvOutput)
        {
            ExcelWorkbook workbook = new ExcelWorkbook(workbookFile);
            try
            {
                // the worksheet index is zero based; the text is saved as UTF-8
                workbook.SaveToCsv(0, csvOutput, ";", Encoding.UTF8);
            }
            finally
            {
                workbook.Close();
            }
        }

        private static ExcelWorkbook LoadEmployees(ExcelWorkbookFormat format, string inputFolder)
        {
            // the CSV fields that are numbers, dates or booleans become number, date and boolean cells (set
            // ParseCSVStrings to false to import all the fields as text); fields of digits with leading zeros,
            // like 00123, stay text
            ExcelWorkbookDefaultSettings settings = new ExcelWorkbookDefaultSettings();
            settings.ParseCSVStrings = true;

            // the fields are parsed with the number and date formats of the current culture, and this CSV file
            // uses the US formats (5/15/1972)
            CultureInfo threadCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
            try
            {
                using (FileStream csvStream = new FileStream(Path.Combine(inputFolder, "Data", "awemployees.csv"), FileMode.Open, FileAccess.Read))
                {
                    // the CSV text encoding, the field separator, and the row and column where the data starts;
                    // the first row of the CSV file (the column names) goes to row 5, column 1
                    return ExcelWorkbook.LoadFromCsv(csvStream, Encoding.GetEncoding(1252), ",", 5, 1, format, settings);
                }
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = threadCulture;
            }
        }
    }
}

Create, edit and read Excel workbooks in a Blazor application: the workbooks are created on the server and downloaded by the browser. The code of each workbook is in the Features folder.