Си sharp как создать xlsx datagridview

от admin

Import and Export Excel to DataGridView in C# and VB.NET

GemBox.Spreadsheet.WinFormsUtilities namespace enables interoperability between GemBox.Spreadsheet and DataGridView control from a Windows Forms application.

The namespace provides a DataGridViewConverter class which you can use to import or export an Excel file to the DataGridView control from C# and VB.NET.

Besides the cell data, some additional information is imported or exported as well, such as hyperlinks, formatting, and images.

Screenshot of an Excel file imported to a Windows Forms application Windows Forms application that imports data from Excel file with GemBox.SpreadsheetScreenshot of a Windows Forms application with imported Excel data

The following example shows how you can export an Excel file into the DataGridView control using the DataGridViewConverter.ExportToDataGridView method and how to import the DataGridView control to an Excel file using the DataGridViewConverter.ImportFromDataGridView method.

See also

Create, read, write Excel files from Classic ASP

Create, read, write Excel files from Classic ASP

Next steps

GemBox.Spreadsheet is a .NET component that enables you to read, write, edit, convert, and print spreadsheet files from your .NET applications using one simple API.

GemBox.Spreadsheet is a .NET component that enables you to read, write, edit, convert, and print spreadsheet files from your .NET applications using one simple API.

Our customers

What do they say

I found your product to be very easy to download, install and use. It took me less than 30 minutes to install GemBox.Spreadsheet and write a C# test program. The API seems very intuitive. I was also impressed by the speed of GemBox.Spreadsheet. I was able to write an Excel data file much, much faster than using Interop.

Being able to include the product directly in my C# project from the NuGet Package Manager has made its installation incredibly easy. So far it has worked brilliantly with a very intuitive API and easy learning curve.

Export DataGridView to Excel C# (Code Example Tutorial)

source code

what is DataGridView?
The control provides a powerful and flexible way to display data in a tabular format. You can use the DataGridView control to show read-only views of a small amount of data, or you can scale it to show editable views of very large sets of data. You can extend the DataGridView control in a number of ways to build custom behaviors into your applications.
For example, you can programmatically specify your own sorting algorithms, and you can create your own types of cells. You can easily customize the appearance of the DataGridView control by choosing among several properties. Many types of data stores can be used as a data source, or the DataGridView control can operate with no data source bound to it.
what is Excel?
Excel is a spreadsheet program from Microsoft and a component of its Office product group for business applications. Microsoft Excel enables users to format, organize and calculate data in a spreadsheet by organizing data using software like Excel, data analysts and other users can make information easier to view as data is added or changed.
Excel contains a large number of boxes called cells that are ordered in rows and columns. Data is placed in these cells. Excel is a part of the Microsoft Office and Office 365 suites and is compatible with other applications in the Office suite. The spreadsheet software is available for Windows, macOS, Android, and iOS platforms.
DataGridView to excel c#
in this article, I will explain with an example, how to export DataGridView data to an Excel file using C#.DataGridView cannot be exported directly to an Excel file and hence need to generate a DataTable dt and export the DataTable to an Excel file. The DataTable will be exported to a formatted Excel file using the ClosedXml library which is a wrapper of OpenXml.for this tutorial, I have already created the database and all the data is in datagridview.
Step # 1: Create Visual Studio Project:
Open Visual Studio. I am using Visual Studio 2019.

Click on Create New Project.
Now, Select Windows Form App from Template, and Press Next, Following Window will appear. Write Project Name. I have written exporting datagridview to excel.
Now, Click Next, Following WIndow will appear.

Source Code

Select .Net Core 3.1 from Dropdown Menu. Click on the «Create» Button, Project will be created.
Step # 2: Install Nuget Package DocumentFormat.OpenXml and ClosedXml Libraries
for this, we need a document open XML sdk and closedXMl library. You can download the libraries using the following download locations.https://github.com/ClosedXML/ClosedXML
Step # 3: Design Window Forms and writes code

Source Code
The design form will look like this I have created a windows form and connected that form with the database and all the data is loaded into the windows forms application.
Importing data to datagridview.
You will need to import the following namespaces before starting the code.
Design form
DataGridView
Inside the Form Load event, the DataGridView is populated with records from the table.
DataGridview
Export DataGridView to Excel
Inside the Button Click event handler, first, a DataTable is created with columns same as that of the DataGridView, and a loop is executed over the DataGridView rows and all the data is added to the DataTable.Then a Workbook object is created to which the DataTable is added as Worksheet using the Add method which accepts DataTable and the name of the Sheet as parameters.
Once the DataTable is added as a Worksheet to the Workbook, the formatting is done by first setting the Header row background color and then applying background colors to the rows and the alternating rows of the Excel file.
Finally, the export data to and export data WorkBook is saved to the specified location on the disk. we can use that workbook as a normal excel documents or workbook. we can also create or fill and export large excel files and normal excel sheets and we can set the filename as well to set the name we have to set the name of the project and then save the name of the file as a string.
Before you write source code, you must add a reference to the Microsoft Excel object library. Right-click on your project and select Add Reference menu. After that go to the COM tab and select and add Microsoft Excel 12.0 object library. Now here is my Button click event handler where I create Excel object sender or object obj and documents, get data from DataGridView, and add rows and columns to the document.
Export data source code sample
Code Sample
sample code
Excel files
after writing the complete source code when we press the export data button the excel file will be generate and when we open the excel file we will get a look like this. all the data of database will be in excel file
Excel file
This is the completion of the guide. I hope it was easy for you to follow and understand. So, what are you waiting for? 30 Days Free Trial You can obtain the License here and begin straightaway. If you are not yet an IronPDF customer, you can try 30-day free trial to check out their available features. If you buy the complete Iron Suite, you will get all 5 Products for the Price of 2. For further details about the licensing, please follow this link to Purchase the complete Package.
You can download the software product from this link.

How to export DataGridView to Excel file in C# and VB.NET

EasyXLS™ library allows you to export a DataGridView to an Excel file. The exported data in cells can be formatted.

EasyXLS can be successfully used inclusively to export large Excel files having big volume of data with fast exporting time.

Table of contents

Source code sample

Step 1: Download and install EasyXLS Excel Library for .NET

To download the trial version of EasyXLS Excel Library, press the below button:

Download EasyXLS™ Excel Library for .NET

If you already own a license key, you may login and download EasyXLS from your account.

Step 2: Create a C# or VB.NET project

If don’t have a project, create one as ASP.NET web application, windows forms app, console application, class library or service.

Step 3: Include EasyXLS library into project

EasyXLS.dll must be added as reference to your project. EasyXLS.dll can be found after installing EasyXLS, in «Dot NET version» folder.

Читать:
Какой компрессор холодильника витрины ариада

Add EasyXLS reference

Step 4: Run C# or VB.NET code that exports DataGridView to Excel

The below example shows how to export DataGridView to Excel in C# and VB.NET from a winform windows application.

Formatting cells

EasyXLS™ enables you to format cells, rows and columns in order to set the fonts and colors.

See also:

How to format Excel cells?

How to use predefined cells format?

Export DataGridView to XLSX, XLSB, XLSM and XLS files

This code sample shows how to export a DataGridView to XLSX file. Similarly, you can export a DataGridView to XLS file using ExcelDocument. easy_WriteXLSFile_FromDataSet method or export DataGridView to XLSB file using ExcelDocument. easy_WriteXLSBFile_FromDataSet method.

See also:

How to export to XLSX file?

How to export to XLSM file?

How to export to XLSB file?

How to export to XLS file?

Export DataGridView to Excel file with multiple sheets

EasyXLS enables you to create multiple sheets for the Excel file and insert the DataGridView inside a specific sheet.

See also:

How to export to Excel file in C# and VB.NET?

How to create multiple sheets?

Export DataTable of DataGridView to Excel file

If the data source of the DataGridView is a DataTable, like in the above sample, the data can be also exported directly from the DataTable.

See also:

How to export DataTable to Excel file in C# and VB.NET?

Getting started with EasyXLS Excel library

To download the trial version of EasyXLS Excel Library, press the below button:

Download EasyXLS™ Excel Library for .NET

If you already own a license key, you may login and download EasyXLS from your account.

Старт работы с 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+ просмотров, то во второй части мы поговорим о том, как можно отделить стилизацию от логики заполнения данными, упростить манипуляции над ячейками и в целом сделаем код боле поддерживаемым.

Похожие статьи