Read from excel epplus

Read write excel in dotnet core 21 epplus

Today in this article we will see the simple approach of Read/Write Excel files in .NET Core using EPPlus.

In our last post, we saw the usage of OpenXML SDK (open source SDK from Microsoft) to work with Office Word, Excel, and PowerPoint using the C# language.

Today, in this article we shall cover the below using EPPLus,

  • You don’t need Microsoft Office
  • Getting Started
  • Read the content of the Excel file using EPPlus
  • JSON to Generic Type Conversion Dynamically
  • Read Excel as JSON output
  • Client-side Code
    • Export/Write the data to an Excel file using EPPlus API
  • Summary

Please see below for your reference,

  • Read/Write excel file .NET Core using OpemXML SDK

EPPLus provides API for working with Office Excel documents.

EPPlus is a .NET library that helps read and write Excel files using the Office OpenXML format. 

This library can be installed from NuGet as a package.

You don’t need Microsoft Office

Please note that Reading and Creating Excel in C# is possible without installing Microsoft Office.

Today we will see a few possible and easy-to-implement approaches.

Getting Started

Let’s create a .NET Core project, you can choose any project template.

EPPlus API works perfectly fine for any .NET Core Project template.

Here to keep it simple I am using a Console .NET Core application.

image

The NuGet Package name is EPPlus.

PM> Install-Package EPPlus 4.5.3.1

[Note: Please use the latest available version]

Let’s look at a simple example, I have a simple Excel file with below columns and rows details. We shall first read this file programmatically.

Please make sure to add below using statements as needed,

using OfficeOpenXml;

Read excel in dotnet core 21

Read the content of the Excel file using EPPlus

Please use the below ‘Ready to Use’ Method in your application.

This method returns the result as a type so that you can read the excel result in the type of your choice.

private static T ReadFromExcel<T>(string path, bool hasHeader = true)
        {
            using (var excelPack = new ExcelPackage())
            {
                //Load excel stream
                using (var stream = File.OpenRead(path))
                {
                    excelPack.Load(stream);
                }

                //Lets Deal with first worksheet.(You may iterate here if dealing with multiple sheets)
                var ws = excelPack.Workbook.Worksheets[0];

                //Get all details as DataTable -because Datatable make life easy :)
                DataTable excelasTable = new DataTable();
                foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
                {
                    //Get colummn details
                    if (!string.IsNullOrEmpty(firstRowCell.Text))
                    {
                        string firstColumn = string.Format("Column {0}", firstRowCell.Start.Column);
                        excelasTable.Columns.Add(hasHeader ? firstRowCell.Text : firstColumn);
                    }
                }
                var startRow = hasHeader ? 2 : 1;
                //Get row details
                for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
                {
                    var wsRow = ws.Cells[rowNum, 1, rowNum, excelasTable.Columns.Count];
                    DataRow row = excelasTable.Rows.Add();
                    foreach (var cell in wsRow)
                    {
                        row[cell.Start.Column - 1] = cell.Text;
                    }
                }
               //Get everything as generics and let end user decides on casting to required type
                var generatedType = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(excelasTable));
                return (T)Convert.ChangeType(generatedType, typeof(T));
            }
        }

JSON to Generic Type Conversion Dynamically

Please refer to this article – logic will generate type dynamically which can be cast to the appropriate type as needed.

Read Excel as JSON output

Excel as JSON will be generated using the below one-liner code.

string strJSON = JsonConvert.SerializeObject(excelasTable)

After executing the above API, The results will be printed on the console as below.

Read excel in dotnet core 21 epplus

Here I have used the simple accessor class UserDetails.

This class will help in serializing and deserializing the Excel data.

public class UserDetails
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

Client-side Code

Below is an example of client-side code,

List<UserDetails> userDetails = ReadFromExcel<List<UserDetails>>(@"C:UsersTestDataRead.xlsx");

Export/Write the data to an Excel file using EPPlus API

Let’s try now exporting data to a new Excel file.

Here is the sample data/object which we want to save as an Excel file.

List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };

Here we need to use ExcelPackage class to create a new excel file with the required details.

Writing data to file and creating new excel is just a 2-3 liner code.

Please make a note of below one line doing the magic of loading DataTable into the Excel sheet

Write export excel in dotnet core 21 epplus

I am creating a new excel file in the same project folder to keep everything simple (the Excel file will get created in the ‘bin’ folder of the project)

private static void WriteToExcel(string path)
        {
            //Let use below test data for writing it to excel
            List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="9999", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="8888", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="7777", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="6666", Name="LMNO", City ="City4", Country="UK"},
           };

            // let's convert our object data to Datatable for a simplified logic.
            // Datatable is the easiest way to deal with complex datatypes for easy reading and formatting. 
            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
            FileInfo filePath = new FileInfo(path);
            using (var excelPack = new ExcelPackage(filePath))
            {
                var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
                ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
                excelPack.Save();
            }
        }

After executing the above API, new Excel file will be created with the above custom object transformation into respective Excel columns and rows details as below,

Write to excel dotnet core epplus

That’s all, we just learned how to import and export data to/from Excel in the .NET Core framework.

Above ready to use API can be used in .NET Core console, or test project or ASP.Net Core application or logic can be modified as per your requirements. Please visit the GitHub link for the complete code.

I have validated the above approaches in .NET Core .NET 3.1 and found it to be working fine in all versions.

Other References:

  • OpenXML SDK (open source SDK from Microsoft) to work with Office Word, Excel, and PowerPoint.
    • Read/Write excel file .NET Core using OpemXML SDK
  • NPOI library for reading and writing excel file in .NET Core,
    • Read/Write Excel files in .NET Core using NPOI

Summary

Today we learned, how to import and export data to/from excel in the .NET Core framework using the EPPlus library.

The legacy so-called applications like Excel are no more legacy and can be used on any platform. EPPlus makes it easy to deal with Excel files allowing us to perform reading or create spreadsheets easily.


Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published best practices and guidelines for software design and development.



Introduction

In this tutorial, i will show you how to read an excel file in C# by using the EPPlus library.

EPPLUS Download and Installation

EPPlus is a .NET library that allows you to read from and write to excel files. To download this library:

1- Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution…

NuGet Package Manager

2- Search for EPPlus.

3- Choose the first search result, check your project and click the install button.

Install EPPlus

4- Click the ok button.

Install EPPlus

EPPLUS Usage

For the purpose of this tutorial, we will use the below excel sample data.

Excel sample data

The following code illustrates how to read the above excel file.

// path to your excel file
string path = "C:/****/sample_data.xlsx";
FileInfo fileInfo = new FileInfo(path);

ExcelPackage package = new ExcelPackage(fileInfo);
ExcelWorksheet worksheet =  package.Workbook.Worksheets.FirstOrDefault();

// get number of rows and columns in the sheet
int rows = worksheet.Dimension.Rows; // 20
int columns = worksheet.Dimension.Columns; // 7

// loop through the worksheet rows and columns
for (int i = 1; i <= rows; i++) {
    for (int j = 1; j <= columns; j++) {

        string content = worksheet.Cells[i, j].Value.ToString();
        /* Do something ...*/
    }
}

In preceding code, we create a new instance of the ExcelPackage by passing the FileInfo object as a parameter of its constructor
, wich enables us to access our excel file. package.Workbook.Worksheets provides access to multiple worksheets. Since our excel file
contains only one worksheet, we use the FirstOrDefault method to access it. After that we loop through our worksheet and we get the value
of each column of each row.

Note: by using the Dimension object, you need to be sure that the excel file you’re working with is not empty.
Otherwise, it will return null.

Namespace

To use EPPlus in your code, you have to include this namespace:

using OfficeOpenXml;

See also

  • Edit an excel file in c#

You can read and write data from and to your spreadsheet in a few different ways. The most obvious is to use the Cells property of the ExcelWorksheet class, shown on the Getting Started page. There are also a few other ways to import/export/read data from/into spreadsheets with EPPlus.

Load data into a spreadsheet

From the Cells property (ExcelRange) you can access these methods to load data from various sources:

  • LoadFromText and LoadFromTextAsync— Read a csv text file and load the data into a range on a worksheet.
  • LoadFromDataReader and LoadFromDataReaderAsync — Loads data into a range from a DataReader
  • LoadFromDataTable — Loads data into a range from a DataTable. Can be used for importing data from a range of sources, like XML (example provided) and databases.
  • LoadFromCollection — Loads data into a range from an IEnumerable using reflection.
  • LoadFromCollection using attributes — Loads data into a range/table from an IEnumerable using reflection. Uses attributes that specifies styling, number formats, formulas, etc.
  • LoadFromDictionaries — Loads data into a range from an IEnumerable of ExpandoObject/dynamic objects (via their IDictionary<string, object> interface. Useful for importing json data, example provided.
  • LoadFromArrays — Loads data into a range from an IEnumerable of object[] where each object array becomes a row in the worksheet.

You can optionally specify a parameter to create an ExcelTable when you use these methods. For more detailed examples, have a look at sample 4 & 5 the sample project Sample-.NET Framework or Sample-.NET Framework.

Export data from a spreadsheet

From the Cells property (ExcelRange) you can access these methods to write:

  • ToText and ToTextAsync — Writes a range to a csv string.
  • SaveToText and SaveToTextAsync — Writes a range to a csv file.
  • ToDataTable — Exports data from a range to a System.Data.DataTable
  • ToCollection — Exports data from a range to an IEnumerable<T> where T is a class.
  • ToJson — Exports data from a range to Json.
  • CreateHtmlExporter — Exports data from a range to html/css.
  • GetValue<T> — Gets a value, with the option to specify a datatype
  • Value — Gets or sets the value of the range.

You can also use the GetValue and SetValue methods directly on the worksheet object.
(This will give a little bit better performance than reading/writing via the range):

  • GetValue<T> — Gets a value of a single cell, with the option to specify a datatype
  • SetValue — Sets a value of a single cell

Since the Cells property implements the IEnumerable interface, you can use Linq to query data from a worksheet.

var query1= (from cell in sheet.Cells["d:d"] where cell.Value is double && (double)cell.Value >= 9990 && (double)cell.Value <= 10000 select cell);

Most of these methods are demonstrated in the sample project.

Example

//create a list to hold all the values
List<string> excelData = new List<string>();

//read the Excel file as byte array
byte[] bin = File.ReadAllBytes("C:\ExcelDemo.xlsx");

//or if you use asp.net, get the relative path
byte[] bin = File.ReadAllBytes(Server.MapPath("ExcelDemo.xlsx"));

//create a new Excel package in a memorystream
using (MemoryStream stream = new MemoryStream(bin))
using (ExcelPackage excelPackage = new ExcelPackage(stream))
{
    //loop all worksheets
    foreach (ExcelWorksheet worksheet in excelPackage.Workbook.Worksheets)
    {
        //loop all rows
        for (int i = worksheet.Dimension.Start.Row; i <= worksheet.Dimension.End.Row; i++)
        {
            //loop all columns in a row
            for (int j = worksheet.Dimension.Start.Column; j <= worksheet.Dimension.End.Column; j++)
            {
                //add the cell data to the List
                if (worksheet.Cells[i, j].Value != null)
                {
                    excelData.Add(worksheet.Cells[i, j].Value.ToString());
                }
            }
        }
    }
}

Содержание

  1. Reading excel with epplus
  2. EPPLUS Download and Installation
  3. EPPLUS Usage
  4. Namespace
  5. Русские Блоги
  6. EPPlus: чтение и запись в Excel на C #
  7. 1. Обзор EPPlus
  8. 2. Введение в основные классы EPPlus
  9. 2.1 Класс ExcelPackage
  10. 2.2 Класс ExcelWorkbook
  11. 2.3 Класс ExcelWorksheet
  12. 2.4 Класс ExcelRange
  13. 2.5 Стиль
  14. 2.6 Числовой формат
  15. Интеллектуальная рекомендация
  16. Poj2796 чувствую себя хорошим одиноким стеком
  17. Начало работы с spring-mvc (1): примеры начала работы
  18. От Дао к Джейн — Душа архитектуры RISC-V (Часть 2)
  19. последовательность очереди
  20. N Вопрос королевы (рекурсивный + обратно) Реализация C ++
  21. Вам также может понравиться
  22. Bluetooth 4.0 BLE Программирование Вопросы, связанные с вопросами решения (воспроизводится)
  23. Напишите скрипт оболочки в Linux и выполните инструкцию Python
  24. Selenium2 испытательный фреймворк идея-03
  25. Командный режим
  26. Одно -гликовая микрокомпьютер (STM32).
  27. Старт работы с Excel на C#
  28. Историческая справка
  29. Задача
  30. Первый запуск
  31. Вывод данных
  32. Стилизация
  33. Размер ячеек
  34. Формат данных
  35. Выравнивание
  36. Стиль текста
  37. Границы
  38. График
  39. Заключение

Reading excel with epplus

In this tutorial, i will show you how to read an excel file in C# by using the EPPlus library.

EPPLUS Download and Installation

EPPlus is a .NET library that allows you to read from and write to excel files. To download this library:

1- Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

2- Search for EPPlus.

3- Choose the first search result, check your project and click the install button.

4- Click the ok button.

EPPLUS Usage

For the purpose of this tutorial, we will use the below excel sample data.

The following code illustrates how to read the above excel file.

In preceding code, we create a new instance of the ExcelPackage by passing the FileInfo object as a parameter of its constructor , wich enables us to access our excel file. package.Workbook.Worksheets provides access to multiple worksheets. Since our excel file contains only one worksheet, we use the FirstOrDefault method to access it. After that we loop through our worksheet and we get the value of each column of each row.

Note: by using the Dimension object, you need to be sure that the excel file you’re working with is not empty. Otherwise, it will return null .

Namespace

To use EPPlus in your code, you have to include this namespace:

Источник

Русские Блоги

EPPlus: чтение и запись в Excel на C #

1. Обзор EPPlus

EPPlus использует OpenOfficeЧтение и запись в формате XML (xlsx)ExcelNET для файлов 2007/2010.

  • Диапазон ячеек
  • Стиль ячейки (граница, цвет, заливка, шрифт, номер, выравнивание)
  • диаграмма
  • образ
  • форма
  • аннотация
  • форма
  • защита
  • шифрование
  • Сводная таблица
  • проверка данных
  • Условное форматирование
  • VBA
  • Расчет формулы
  • Больше.

2. Введение в основные классы EPPlus

2.1 Класс ExcelPackage

ExcelPackage — это начальный класс EPPlus, который анализирует файл Excel и создает объект ExcelWorkbook для представления Excel. Этот класс реализует интерфейс IDisposable, что означает, что вы можете использовать using для выпуска объекта.

10 конструкторов, из них 3 обычно используются:

Независимо от того, допустимы ли параметры, переданные в конструкторе, свойство Workbook этого класса будет создано автоматически, поэтому нет необходимости беспокоиться о проблеме с нулевым указателем.

2.2 Класс ExcelWorkbook

Класс ExcelWorkbook представляет файл Excel, а его атрибут Worksheets соответствует каждому листу Excel. Свойство Worksheets будет создано автоматически, поэтому не беспокойтесь об исключении нулевого указателя, но его Count может быть равен 0.

Свойство Properties ExcelWorkbook может устанавливать некоторые свойства Office, например:

Примечание. При получении определенного листа номер индекса начинается с 1, например:

2.3 Класс ExcelWorksheet

Некоторые общие атрибуты:

Добавлять и удалять операции по рангам:

Установите стиль указанной строки или столбца (ширина, высота, скрытый, автоматический перенос строк, числовой формат, блокировка и т. Д.):

sheet.Column(1).Width = 10; sheet.Row(1).Height = 30; sheet.Column(1).Hidden = true; sheet.Row(1).Hidden = true; sheet.Column(1).Style.WrapText = true; sheet.Column(1).Style.Numberformat.Format = «$#,###.00»; sheet.Row(1).Style.Locked = true;

Настройка адаптивной ширины:

2.4 Класс ExcelRange

3 способа получить диапазон ячеек:

Загрузите данные из двухмерного набора данных:

public ExcelRangeBase LoadFromCollection (IEnumerable Collection); public ExcelRangeBase LoadFromDataReader (IDataReader Reader, bool PrintHeaders); public ExcelRangeBase LoadFromText (FileInfo TextFile); // Файл здесь ссылается на файл CSV // Когда данные загружаются, он будет Соответствуя строкам и столбцам ExcelRange, установите для него значение, эти ячейки не имеют стиля и числового формата

2.5 Стиль

Стиль включает шрифт, цвет, выравнивание, границу и т. Д.

2.6 Числовой формат

При использовании цифрового формата вы должны сами проверить правильность формата, потому что EPPlus не будет проверять его правильность в процессе генерации. Если формат неправильный, при открытии сгенерированного файла Excel появится сообщение о неправильном формате файла.

Такие же меры предосторожности применяются при использовании формул и числовых форматов, и вам нужно проверить правильность самостоятельно.

Рекомендуется всегда записывать, сколько строк и столбцов должен иметь текущий лист, чтобы упростить позиционирование ячеек при использовании формул.

Рекомендуется прокомментировать код, связанный с формулой, чтобы помочь другим программистам понять.

Интеллектуальная рекомендация

Poj2796 чувствую себя хорошим одиноким стеком

http://poj.org/problem?id=2796 Значение: требует поиска диапазона значения, интервальное значение, определенное как минимум интервала интервала и умножения. Практика: непосредственно нашел интервалы с.

Начало работы с spring-mvc (1): примеры начала работы

введение 1.MVC :Model-View-Control РамообразнойC Основная работа, которую необходимо выполнить на уровне: инкапсуляцияweb Запрос является объектом данных, вызывает уровень бизнес-логики для обработки .

От Дао к Джейн — Душа архитектуры RISC-V (Часть 2)

Эта статья входит в серию статей «Проектирование ЦП RISC-V» и «Разработка встроенного программного обеспечения RISC-V». Примечание. Эта статья представляет собой отрывок из пер.

последовательность очереди

При написании кода вам необходимо добавить заголовочный файл «очередь», за которым следует #include «алгоритм». с использованием пространства имен std; также есть q, pop () при.

N Вопрос королевы (рекурсивный + обратно) Реализация C ++

N Вопросы королевы (рекурсивный + назад N Queens, выпущенные технологией функции имитации C ++: Решить класс проблем: Основная функция: результат Результаты здесь опущены, и существует 92 консенсус бе.

Вам также может понравиться

Bluetooth 4.0 BLE Программирование Вопросы, связанные с вопросами решения (воспроизводится)

Q: Что такое связь Bluetooth? A: Оригинальный дизайн связи Bluetooth заключается в том, чтобы облегчить низкую стоимость между мобильными телефонами (мобильными телефонами) и аксессуарами, беспроводны.

Напишите скрипт оболочки в Linux и выполните инструкцию Python

Статус -кво спроса: вам нужно написать сценарий, и некоторые вызовы сценария Python инкапсулируются в скрипте Пример Описание: Напишите скрипт оболочки на платформе Linux, а затем регулярно вызовите. .

Selenium2 испытательный фреймворк идея-03

Фактически, в процессе нашего тестирования мы обнаружим, что существует множество проблем с данными, которые необходимо решить. Например, верны ли данные, возвращаемые на странице? Данные полны? Нам в.

Командный режим

Определения Командный режим инкапсулирует запросы в объекты, чтобы можно было использовать разные запросы, очереди или журналы. Оцифровка других объектов. Командный режим также поддерживает отмену опе.

Одно -гликовая микрокомпьютер (STM32).

Одно -гликовая микрокомпьютер (STM32). Эта статья представляет собой запись опыта личного обучения, что удобно для будущего обзора, а также предоставляет удобство для других друзей. У меня ограниченна.

Источник

Старт работы с Excel на C#

В современном мире разработки приложений нередко встает необходимость работы с Excel документами. Чаще всего это разного рода отчеты, но иногда xls/x файлы используются в качестве хранилища данных. Например, если пользователь должен иметь возможность загрузить данные в приложение или выгрузить, в человеко-читаемом виде, Excel де-факто является стандартом. Относительно дружелюбный интерфейс, прозрачная структура, в купе с его распространенностью. трудно навскидку назвать решение лучше.

Однако, у многих Excel до сих пор ассоциируется с чем-то тяжелым, неповоротливым и сложным. Давайте посмотрим, как мы — обычные C# разработчики, можем легко сформировать простой Excel документ, на примере табличного отчета.

Историческая справка

Времена, когда доминировал проприетарный формат .xls(Excel Binary File Format) давно прошли и сейчас мы имеем только .xlsx(Excel Workbook), в рамках Office Open XML. Последний представляет собой обычный .zip архив с XML файлами. Не будем углубляться в его структуру, я искренне надеюсь что вам это никогда не понадобится.

На github, и не только, можно найти ряд библиотек, бесплатных и не только. Пожалуй самой популярной является EPPlus. До определенной степени, она довольно хорошо отражает концепцию Excel, именно по этому я всегда использую EPPlus. Версия 4 полностью бесплатна, начиная с 5‐й версии вам потребуется приобрести лицензию для коммерческого использования.

Задача

Итак, предположим, продукт-мэнеджеру ударила в голову идея того, что возможность выгружать некий отчет в формате Excel увеличит кол-во пользователей на 100500%. Проджет-менеджер решает выкатить эту киллер-фичу как хотфикс прямо сегодня — ведь работы всего на пару часов.

Сам по себе, отчет содержит краткое описание компании и историю изменения некоторых экономических показателей. Для простоты все свойства компании — строки. Экономические показатели — большие целые числа и числа с плавающей точкой, а также даты. Предположим, что где-то в недрах микросервисного backend-да есть сервис-генератор подобных отчетов, например по id компании. Однако, поскольку id нет смысла выводить пользователю, идентификатор отсутствует в самой модели отчета.

Аналитик, в свою очередь, выдает задачу с феноменально точным описанием — «Сгенерировать excel отчет на базе данных MarketReport». Что ж, для нашего примера, создадим заглушку — генератор фейковых данных:

Первый запуск

Подключим EPPlus версии 4.5.3.3 и создадим базовую обвязку для будущего генератора.

Сердцем генератора будет метод Generate. ExcelPackage это модель документа, через которую мы и будем осуществлять все взаимодействия с ним. Также имеется конструктор для передачи пути к файлу или потока.

В методе main создается генератор отчетов, а также генератор Excel файлов. Далее полученный файл просто записывается на диск.

При попытке запустить приложение, получаем exception: InvalidOperationException: The workbook must contain at least one worksheet

Все правильно, Excel документ не может существовать без страниц, должна быть хотя бы одна. Добавляем ее, все интуитивно понятно:

Запускаем снова и. вот оно! Теперь наше приложение генерирует документ и, хотя там еще ничего нет, он уже весит 2,5KB — значит мы работаем с Excel правильно и все идет как надо.

Вывод данных

Давайте выведем основную информацию по компании в шапку. Для доступа к конкретной ячейки объект Cells на странице пакета снабжен удобным индексатором. При этом, до конкретной ячейки можно достучаться как через номер строки и столбца, так и по привычному всем буквенно-числовому коду:

Полный код вывода шапки.

Для вывода исторических данных понадобится как минимум шапка таблицы и цикл по массиву History:

Предлагаю обратить внимание на метод LoadFromArrays, который заполняет диапазон ячеек рваным(зубчатым) массивом. Здесь мы можем видеть, что типизация теряется и передавая массив object мы ожидаем что EPPlus в конечном итоге использует ToString, чтобы записать переданное в ячейки.

Стилизация

Если вы прямо сейчас откроете документ, то вы возможно увидите не то, что хотелось бы отдать в продакшн в пятницу вечером.

Как это выглядит

Во-первых, шапка никак не выделяется, во-вторых таблица не имеет границ. выравнивание пляшет, даты отображаются магическими числами, а капитализация «уходит в какую-то математику» — как это прокомментировал аналитик.

Да, на все эти красивости у нас уйдет больше года кода, чем на сам вывод данных, и, в конечном тоге, получившаяся каша из логики вывода данных и разметки заставит некоторых усомниться в их компетентности. но, мы же backend разработчики, так давайте сверстаем Excel Sheet!

Размер ячеек

Из коробки у нас есть возможность сделать автофит а так же вручную выставить ширину в соответствии с нашей ситуацией. А ситуация у нас не самая хорошая — по задумке аналитика в шапке у ячеек должен быть автофит, а у ячеек таблицы — тоже автофит. Так в чем же подвох?

Если вы когда-нибудь до этого открывали Excel, то возможно знаете, что ширина ячеек не может отличаться в рамках столбца и автофит будет по самому широкому контенту ячейки. Однако, простые вещи бывает нетак то просто объяснить. Но если вы справитесь, то вот как это будет выглядеть в коде:

Формат данных

Как и большая часть стиля ячейки, он задается через одноименное свойство Style. Обратите внимание на вычисление 3-го аргумента индексатора. Это звоночек некачественного кода, но к этому мы вернемся в позже.

Выравнивание

Его можно задать как на ячейке, так и на диапазоне. На самом деле, для EPPlus, это одна и та же сущность — некий ExcelRange, описывающий диапазон ячеек, в том числе и со всего 1 ячейкой.

Стиль текста

Также легко задается, используя Style.Font, кстати, здесь, на 2-й строчке, мы впервые указываем диапазон так, как привыкли его видеть пользователи Excel:

Границы

Задаем стиль линии, а также ее толщину. К этому моменту от кол-ва магических чисел-параметров индексатора уже рябит в глазах, но мы уже на финишной прямой. не так ли?

График

«Ну что за отчет без графиков, верно, Карл?» — ловко подметит специалист по тестированию, и не важно, что этого не было в ТЗ а на часах уже половина 9-го.

Хотя график как сущность сам по себе сложнее таблиц и с графиками мы не работаем каждый день, EPPlus предоставляет довольно понятный API. Давайте добавим простейший график, отражающий рост капитализации:

Еще, может понадобиться защитить страницу от редактирования:

На этом все, репозиторий с рабочим приложением находится здесь.

Заключение

Во-первых, прежде всего, о том, что мы успешно справились с задачей, а именно, сгенерировали свой первый Excel отчет, поработали со стилями и даже решили пару попутных проблем.

Во-вторых, возможно имеет смысл искать новою работу, но, забегая вперед, я бы с этим не спешил. Если данная публикация наберет 1+ просмотров, то во второй части мы поговорим о том, как можно отделить стилизацию от логики заполнения данными, упростить манипуляции над ячейками и в целом сделаем код боле поддерживаемым.

Источник

Whether you are working on Windows or on Web or on Console application, at one stage we need to process data and excel file is widely used for it, so in previous article, we have explained about creating excel in C# without interop but in this article, I am going to provide you code to open and read excel file (.xls or .xlsx) in C# line by line in Console application using OLEDB or EPPlus or Interop (all 3 methods), you can use the same code C# code to fill ASP.NET GridView or MVC application table.

So, let’s get started with it.

Step 1: Create a new Console applicaiton in your Visual Studio, by navigating to File->New->Project-> Select «Windows Classic dekstop» from left-pane & «Console-App» from right-pane -> Provide a name to your application «CSharpReadExcelFile» -> Click «OK»

c-sharp-read-excel-min.png

Step 2: Now we have our Console application and we need to add C# code using OLEDB to read excel file, for that we would need connection string with the source URL of excel file.

In the given example as I am using .XLS excel file, here is my connection string

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Sample1.xls; Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";

For Excel 97-2003 Format we can use “Microsoft Jet OLEDB Driver 4.0”, while for the Connection String for Excel 2007 Format (.XLSX), we can use “Microsoft Ace OLEDB Driver 12.0” and it’s connection string would be as below

 string connString = "Provider= Microsoft.ACE.OLEDB.12.0;" + "Data Source=Sample1.xlsx" + ";Extended Properties='Excel 8.0;HDR=Yes'";

In the above Connection string’s you may see extended properties HDR=Yes & HDR =No

Use HDR=YES if first excel row contains headers, alternatively,use HDR=NO when your excel’s first row is not headers and it’s data.

Now, we have connection string , we need to create connection using OLEDB and open it

             // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
           
            // Open connection
            oledbConn.Open();

Read the excel file using OLEDB connection and fill it in dataset

  //here sheet name is Sample-spreadsheet-file, usually it is Sheet1, Sheet2 etc..
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sample-spreadsheet-file$]", oledbConn);

                // Create new OleDbDataAdapter
                OleDbDataAdapter oleda = new OleDbDataAdapter();

                oleda.SelectCommand = cmd;

                // Create a DataSet which will hold the data extracted from the worksheet.
                DataSet ds = new DataSet();

                // Fill the DataSet from the data extracted from the worksheet.
                oleda.Fill(ds, "Employees");

in the above code Sample-spreadsheet-file is the name of Sheet.

Note: With the help of sheet name, you can refer to Excel data, you need to use ‘$’ with sheet name, e.g. Select * from [Sheet1$]

Now loop through each row of excel sheet and print it in Console app

 //loop through each row
                foreach(var m in ds.Tables[0].DefaultView)
                {
                    Console.WriteLine(((System.Data.DataRowView)m).Row.ItemArray[0] +" "+((System.Data.DataRowView)m).Row.ItemArray[1] +" "+((System.Data.DataRowView)m).Row.ItemArray[2]);

                }

If you are using ASP.NET, you can bind it with Grid View using below code instead of printing it

            // Bind the data to the GridView
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();

Now, we have discussed each step, suppose this is out Excel file

/sample-xls-file-read-csharp-min.png

and ese the code below in your Console application, build and execute it.

using System;
using System.Data;
using System.Data.OleDb;


namespace CSharpReadExcelFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //this is the connection string which has OLDB 4.0 Connection and Source URL of file
            //use HDR=YES if first excel row contains headers, HDR=NO means your excel's first row is not headers and it's data.
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Sample1.xls; Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";
          

            // Create the connection object
            OleDbConnection oledbConn = new OleDbConnection(connString);
            try
            {
                // Open connection
                oledbConn.Open();

                // Create OleDbCommand object and select data from worksheet Sample-spreadsheet-file
                //here sheet name is Sample-spreadsheet-file, usually it is Sheet1, Sheet2 etc..
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sample-spreadsheet-file$]", oledbConn);

                // Create new OleDbDataAdapter
                OleDbDataAdapter oleda = new OleDbDataAdapter();

                oleda.SelectCommand = cmd;

                // Create a DataSet which will hold the data extracted from the worksheet.
                DataSet ds = new DataSet();

                // Fill the DataSet from the data extracted from the worksheet.
                oleda.Fill(ds, "Employees");

                //loop through each row
                foreach(var m in ds.Tables[0].DefaultView)
                {
                    Console.WriteLine(((System.Data.DataRowView)m).Row.ItemArray[0] +" "+((System.Data.DataRowView)m).Row.ItemArray[1] +" "+((System.Data.DataRowView)m).Row.ItemArray[2]);

                }
           
            }
            catch (Exception e)
            {
                Console.WriteLine("Error :" + e.Message);
            }
            finally
            {
                // Close connection
                oledbConn.Close();
            }
        }
    }
}

Output of the above code will be as below

csharp-read-excel-file-xls-min.png

Now, if you are working on 64 bit operating system, you may get this error «The ‘Microsoft.Jet.OLEDB.4.0’ provider is not registered on the local machine.«.

Resolving this error: If your application is Desktop based, compile your EXE with x86 CPU (Menu Tools, Options, select Projects And Solutions, check the show advanced build configurations. Now in the Build Menu you will be able to go to the Config Manager and set output to x86.)

If your application is web based, then Enable ’32-Bit Applications’ in application pool.

On IIS, change the «Enable 32-bit Applications» setting to True, in the Advanced Settings for the Application Pool.

Disadvantage of using OLEDB for Excel

With OLEDB, you cannot format data that you inserted/updated in EXCEL sheet but Interop can do it efficiently. You cannot perform any mathematical operation or working on graphs using OLEDB, but it is really a good way to insert/update data in EXCEL where no Excel application is installed.

Reading Excel file using EPPlus

If you don’t want to use OleDb, you can try using EPPlus Nuget package based solution.

For this, you would have to install EPPlus, so navigate to «Tools»-> «Nuget package manager»-> «Manage Nuget for this solution» -> Select «Browse» tab and search for «EPPlus», then install the nuget package.

c-sharp-read-excel-file-epplus-example

Once you have installed the package, in your Console application «Program.cs», you can use the code below

using OfficeOpenXml;
using System;
using System.IO;


namespace ReadExcelInCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            //provide file path
            FileInfo existingFile = new FileInfo(@"D:sample_XLSX.xlsx");
            //use EPPlus
            using (ExcelPackage package = new ExcelPackage(existingFile))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        //Print data, based on row and columns position
                        Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
                    }
                }
            }
        }
    }
}

Here is the image, which shows console application output with sample excel file (.xlsx), we are using .xlsx file here for reading in C# using EPPlus

epplus-sample-read-excel-c-sharp-min.png

You can use above EPPlus example to work in .NET Core C# also, to read excel file in .NET Core.

Read Excel using MS Office Interop

You can also read Excel file in C# using MS Office Interop easily.

First you will have to add reference for «Microsoft.Office.Interop.Excel«, so in your Console, Windows or Web-Application, right-click on «Reference» and then in «Assemblies» search for «Microsoft.Office.Interop.Excel»

read-excel-ms-office-csharp.png

So, here is the C# Code for it, considering we have sample XLSX file as above

using Microsoft.Office.Interop.Excel;
using System;

namespace ReadExcelCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Application excelApp = new Application();
            if (excelApp != null)
            {
                Workbook excelWorkbook = excelApp.Workbooks.Open(@"D:sample_XLSX.xlsx", 0, true, 5, "", "", true, XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
                Worksheet excelWorksheet = (Worksheet)excelWorkbook.Sheets[1];

                Range excelRange = excelWorksheet.UsedRange;
                int rowCount = excelRange.Rows.Count;
                int colCount = excelRange.Columns.Count;
                //get an object array of all of the cells in the worksheet (their values)
                object[,] valueArray = (object[,])excelRange.get_Value(
                            XlRangeValueDataType.xlRangeValueDefault);

                for (int i = 1; i <= rowCount; i++)
                {
                    for (int j = 1; j <= colCount; j++)
                    {
                     

                        Console.WriteLine(valueArray[i, j].ToString());
                    }
                }

                excelWorkbook.Close();
                excelApp.Quit();
            }
        }
    }
}

Output:

read-excel-csharp-interop.png

As you can see we have used Interop to open and read excel rows/columns, one of the drawbacks of using MS office Interop is that you need it installed on Server also.

You may also like to read:

Read Excel file and import data into GridView using Datatable in ASP.NET

Read file in C# ( Text file example using Console Application )

That’s it, feel free to provide your feedback in the below comment’s section.

Introduction 

This article is about reading data from Excel and appending extra data without saving a physical path using the EPPlus package.

EP Plus is a open-source 3rd party DLL . We use the EP Plus package to write data to excel sheet. It supports multiple properties of spreadsheets, like cell ranges, cell styles, data validations, comments, etc. The library is available for use via NuGet.

The following Classes are available in EP Plus Package:

Name Description
ExcelPackage Reprasent Excel 2007/2010 XLSX file package
ExcelAddress Range address with the address property
ExcelAddressBase A range address
ExcelBackgroundImage Am image that files the background of worksheet
ExcelAddressCell A single cell address
ExcelCellBase Base class containg cell address manipulating methods
ExcelColumn Reprasents one or more columns with the worksheet
ExcelComment An ExcelCell Comment
ExcelCommentCollection Collection of Excelcomment objects
ExcelEncryption How and if the workbook is encrypted
ExcelHeaderFooter Reprasents header and footer on an Excel worksheet
ExcelHeaderFooterText Print header and footer
ExcelHyperLink HyperlinkClass
ExcelNamedRange A named range
ExcelNamedRangeCollection Collection of named ranges

For reading data from an excel sheet and adding extra data, we have to use the ExcelPackage class.

Create a WebAPI Project.

File —> new —> Project —>ASP.NET Web Application and give name EPPlusExcel

Select Empty application and web API

 

After Creating Web API right click on the Controllers folder add the new controller (ProxyController.cs)

Right-click on the project —>Manage NuGet Packages —> search for EPPlus and install latest version of package

 

Add the Code in Post method for reading data bytes, and then append the extra data into Excel.

MemoryStream

The MemoryStream class creates streams that have a memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a memory stream object, or an array can be created as empty.

A memorystream is constructed from this byte array containing the byteexcel’s data

ExcelPackage

The first thing you do is to create an instance for the ExcelPackage Class. To do that, you first need to add a using directive to OfficeOpenXml namespace at the top of your file (Namespace block). This is the top namespace in EP Plus.

The following syntax is used for byte data to ExcelPackage through MemoryStream

Syntax

  1. ExcelPackage package=new ExcelPackage(memoryStreamObject);  

Now Excelpackage has a workbook with byte data in the form of worksheets, where we can add multiple worksheets data as a bulk.

 

Build the application and test the API through Postman or filler…

  • Remove From My Forums
  • Question

  • hi,

    I am using bellow code to read the data from excel file

       FileInfo fileInfo = new FileInfo(filePath);
       ExcelPackage excl = new ExcelPackage(fileInfo );

     foreach (ExcelWorksheet sht in excl.Workbook.Worksheets)

    {

    ….

    }

    Above code works only xlsx and xlsm format file but not works for xls format.

    Can anyone help me to use the same EPPlus library to read data from XLS format excel file?

    Thanks

    Arivazhagan K

    • Moved by

      Friday, September 29, 2017 1:19 PM
      Moved From Visual C#

Понравилась статья? Поделить с друзьями:
  • Read file from excel in java
  • Read faster one word at a time
  • Read fast one word at a time
  • Read excel with epplus
  • Read excel table python