Перейти к содержимому

Winforms таблица как в excel

  • автор:

Creating an Excel-like Formula Bar in .NET WinForms

The ComponentOne Calculation Engine “C1CalcEngine”, a .NET Standard library that enables parsing and computing expression/formulas, is available for all ComponentOne .NET platforms and can be used to facilitate formula calculation.

The library is equipped with many advanced features, like extensive calculation support for business objects, an out-of-the-box expression parser for parsing text expressions that follow the Microsoft Excel format, and more.

excel like
Image shows Excel-styled expression in Excel-like formula bar along FlexGrid.

One such advanced feature is Cross-worksheet reference. This article will walk through how this feature can be used in building Excel-like Formula Bar in .NET WinForms application.

What is Cross-worksheet Cell Reference?

A cell reference is a set of coordinates that specify a cell/cell range position on a worksheet. Cell references in formulas are used to obtain and process data contained in the corresponding cells. One advantage of using references is that the formulas’ results are automatically updated each time the values of these cells change.

Additionally, there are scenarios where data is distributed among multiple sheets. In such situations, cells can reference cells located in other worksheets. This is where the C1CalcEngine cross-worksheet referencing feature is helpful.

To refer to cells in another worksheet, identifying the target cell/cell-range is needed, but the sheet where the cells are located needs to be identified. To do this, like Excel, the target worksheet name is defined before the cell/cell-range reference, separated by an exclamation point (!).

Here, the expression uses two sheets, “sheet1” and “sheet2,” and applies mathematical functions “Sum” and “Max”, respectively.

How to Create Excel-like Formula Bar

In Excel, the Formula Bar is a visual element that allows end-users to edit data values and formulas contained in worksheet cells.

formula bar
The image shows the Formula Bar component in MS Excel.

Using C1CalcEngine, it’s easy to add Excel-like Formula Bar behavior in your .NET application. Let’s see how.

Steps

As a non-UI component, C1CalcEngine does not provide any visual components to display on the form. Therefore, to stimulate the Formula Bar behavior in your WinForms application and define formulas similar to Excel, you will need to build your own formula bar.

To build an Excel-like Formula bar, you can use TextBox and Button controls to display/enter expressions and use C1CalcEngine to parse these expressions for calculations. The steps below demonstrate how to add an Excel-like formula bar in your .NET WinForms application from scratch.

We’ll be dividing the complete implementation into the following parts:

  • Setting up application
  • Adding References to libraries
  • Creating DataSource
  • Binding C1CalcEngine to DataSource
  • Assigning Excel-styled Expressions
  • Evaluating Expressions using C1CalcEngine

Setting Up the Application

  1. Create a new Windows Forms Application and name it _CalcEngine_CrossShee__t_.
  2. Add a TextBox control to display the expression.
  3. Add a Button control to trigger the expression’s parsing and set its “Text” property to Evaluate.
  4. Add a Label control to the Form and set its “Text” property to Result.
  5. Add another TextBox control to display the expression evaluation result.
  6. For illustration, add two FlexGrid controls to the Form to represent two Excel-worksheets that contain cross-reference.

post completion form

Post-completion of this step, the form should look similar to the above image.

Add References

  1. Install C1CalcEngine NuGet package using NuGet Package Manager.
  2. Switch to the code view and add the following namespaces:

Create Data Source

To use cross-sheet references, all referenced worksheets should be passed as a data source for C1CalcEngine, and each element of the list will act as a sheet for C1CalcEngine. The expressions evaluated by the C1CalcEngine use these sheets and their names to implement cross-sheet referencing.

Therefore, let’s create a custom DataTable that implements the IDataSheet interface, to be used as FlexGrid’s DataSource. This generates a bound FlexGrid control to be used as a DataSource for C1CalcEngine.

Bind CalcEngine to Data Source

Define C1CalcEngine and a string variable globally using the following code:

Add the following method to initialize SheetTable class to be used as C1FlexGrid’s DataSource:

Use the method defined above to generate FlexGrids’ DataSource and use the sheets as C1CalcEngine’s DataSource:

Assign Expression

To update Formula bar (expression textbox) as the selection changes in worksheets (FlexGrid), handle the SelChange event of FlexGrid controls. Define the event handler as follows to generate C1CalcEngine expressions based on the current selection of FlexGrid instances.

Define the following method to translate the FlexGrid selection to Excel expression notation so that it gets evaluated by C1CalcEngine:

formula sample bar
The image shows the formula bar with a sample expression.

Evaluate Result

To evaluate the created Excel-styled expressions, use the TryEvaluate method of the C1CalcEngine class. For this, handle the Click event of the button and add the following code to it:

Be sure to download the sample application and try using it in your use case scenario. If you have any suggestions, feel free to leave a comment below.

Winforms таблица как в excel

как перебрать таблицу exel что б можно показать ее например в listView или DataGridView?

winamorinw's user avatar

Рекомендую использовать сторонние библиотеки, поддерживающие формат xlsx. Использовать Interop не рекомендую (в основе его лежит медленный COM и требуется наличие MS Office).

Использовал библиотеку EPPlus. Она бесплатна для некоммерческого использования. Позволяет читать ячейки, а можно загрузить диапазон ячеек в DataTable.

Добавьте nuget пакет EPPlus в ваше приложение, а далее используйте вышеуказанные примеры кода для чтения Excel.

Алексей Обухов's user avatar

Считай все ячейки из документа и поставь как контент датагридвью.

Если ты умеешь пользоваться 2хмерным масивом и датагридвьюхой — у тебя проблем не возникнет в принципе, если воспользуешся вот этим ответом:

Andrew Stop_RU_war_in_UA's user avatar

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.5.25.43461

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

WinForms Excel Library

WinForms Excel Library allows to host MS Excel interface in Windows Forms application as a user control in order to display and edit one or more tables of data. The Excel application is started in different process, but the interface is fully integrated into your application as for any usual control. Basically, it works like DataGridView, but enables user to take advantage of various data processing and visualization capabilities of MS Excel, which might be useful in scientific, engineering or financial applications. The library interacts with Excel via Primary Interop Assemblies. Currently implemented functionality:

  • Filling data from files, DataTable objects or manually on cell-by-cell basis;
  • Displaying and editing one or several tables in your form in Excel GUI;
  • Getting data back as DataTable objects or getting the content of specific cells;
  • Saving data into file;
  • Adding charts;
  • Manipulating worksheets: adding, deleting, reordering, changing names, changing active sheet;
  • Showing/hiding Excel formula bar and status bar;
  • Direct access to Excel interoperability interfaces via Application object.

The library distribution package contains demo application project (Visual Studio 2010)

.NET Framework 4.0+ or .NET Core 3.1+ (must be present on target machine)

MS Excel 2003+ (must be present on target machine)

Visual Studio 2010+ (for .NET Framework) or Visual Studio 2019+ (for .NET Core)

Usage

The library functionality is provided via ExtraControls.AdvancedDataGrid user control. In order to use it in WinForms application, do the following:

1. Copy WinFormsExcel.dll, Interop.Excel.dll, Interop.Microsoft.Office.Core.dll assemblies in your project, and add reference to WinFormsExcel assembly.

2. Open Windows Forms designer, right-click toolbox, click "Choose elements". Click "Browse", and choose WinFormsExcel.dll. AdvancedDataGrid will appear in "NET Components" list.

3. Check AdvancedDataGrid and click OK. AdvancedDataGrid will appear in toolbox under "Other" category.

4. Drag AdvancedDataGrid onto the form.

5. Adjust control’s appearance properties such as border, background color, to distinguish it visually from form’s background.

Note: control will look empty in designer, because Excel is not initialized yet.

6. Place advancedDataGrid.InitializeExcel() method call in your form’s constructor or OnLoad event (this will create Excel process)

7. Fill the grid with data using one of the following methods:

public void OpenFile(string file);

public void SetCellContent(int sheet, int row, int col, object val);

public void SetSheetContent(int sheet, DataTable t);

Receive user input via one of the following methods:

public DataTable GetSheetContent(int sheet, bool FirstRowHasHeaders,int n_col=0,int n_row=0);

public object GetCellContent(int sheet, int row, int col);

Use other functionality, such as manipulating sheets, adding charts, or saving data to file. Note that sheet indices start from 1 in excel, and charts are treated as sheets as well.

When you no longer need the control (for example, in FormClosing event), call advancedDataGrid.Destroy() method to clean up resources.

If you need your application to be work on machines without MS Excel installed (with lesser functionality), use C_AdvancedDataGrid control instead. It’s a wrapper that uses AdvancedDataGrid if Excel is present, otherwise it substitutes its functionality with a combination of standard controls.

Создать Excel в visual studio c#

Давайте научимся быстро и просто создавать и записывать файлы Excel с помощью visual studio c#. Наше самое простое приложение Windows Forms будет брать из текстбокса текст и заносить его в первую ячейку. Статья написана специально для Сергея =).

Начать необходимо с подключения библиотеки Microsoft.Office.Interop.Excel. Выглядеть это должно так:

Если у вас при открытии обозревателя решений – Ссылки – правая кнопка – Добавить ссылку – Сборки – в списке нет Microsoft.Office.Interop.Excel, то добавьте её через Nuget. Проект – управление пакетами NuGet – в строке поиска Excel:

Теперь создайте новый проект Windows Forms и на форму закиньте текстбокс и кнопку. На кнопки кликните два раза, откроется исходный код. В самом верху допишите следующее:

А в методе button1_Click замените так:

Вот, собственно говоря и все. Текст из текстбокса запишется в ячейку A1. Обратите внимание, что папка temp на диске уже должна существовать.

Дополнение. Прочитать первую ячейку

Это тоже просто:


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

WinForms Excel Library (.NET Component)

If you need your application to be work on machines without MS Excel installed (with lesser functionality), use C_AdvancedDataGrid control instead. It’s a wrapper that uses AdvancedDataGrid if Excel is present, otherwise it substitutes its functionality with a combination of standard controls.

Reference

public bool DisplayWindowTitle

Determines whether control should display Excel’s window title, including ribbon menu in new versions

Visible in designer. Default value: false

public interface IDataGrid

Provides a set of properties and methods shared by DataGrid controls able to display multiple data tables. The library contains several implementations: AdvancedDataGrid, S_AdvancedDataGrid , C _AdvancedDataGrid . See AdvancedDataGrid description for more information about the meanings of these properties and methods.

void SetCellContent ( int sheet, int row, int col , object val );

object GetCellContent ( int sheet, int row, int col );

void SetSheetContent ( int sheet, DataTable t);

DataTable GetSheetContent ( int sheet, bool FirstRowHasHeaders , int n_col = 0, int n_row = 0);

void SetActiveSheet ( int index);

void DeleteSheet ( int index);

void AddSheet ( string name = «» );

List < XlSheet > GetSheets ( );

void SetSheetName ( int sheet, string name);

string GetSheetName ( int sheet);

int FindSheet ( string name);

public class C_AdvancedDataGrid : UserControl , IDisposable , IDataGrid

Wrapper control for AdvancedDataGrid/ S_AdvancedDataGrid controls. Switches between them at runtime, allowing to use required control depending on Excel presence on the target machine.

Creates C_AdvancedDataGrid control in substitute mode

public C_AdvancedDataGrid ( GridMode mode)

Creates C_AdvancedDataGrid control in specified mode

public GridMode Mode

Gets or sets the current grid mode. Setting this property will cause control to be initialized again.

public IDataGrid BaseGrid

Returns the underlying grid, which type is determined by Mode property

public void Initialize( GridMode mode)

Initializes this control in specified mode

public void Destroy()

Releases resources associated with this control instance.

Members from IDataGrid interface:

void SetCellContent ( int sheet, int row, int col , object val );

object GetCellContent ( int sheet, int row, int col );

void SetSheetContent ( int sheet, DataTable t);

DataTable GetSheetContent ( int sheet, bool FirstRowHasHeaders , int n_col = 0, int n_row = 0);

void SetActiveSheet ( int index);

void DeleteSheet ( int index);

void AddSheet ( string name = «» );

List < XlSheet > GetSheets ( );

void SetSheetName ( int sheet, string name);

string GetSheetName ( int sheet);

int FindSheet ( string name);

See AdvancedDataGrid description for the information about the meaning of these methods.

Determines the behavior of C_AdvancedDataGrid control.

Undefined = 0, //not initialized yet

Auto = 1, //Choose mode automatically: Excel mode if possible, otherwise Substitute

Excel = 2, //Uses AdvancedDataGrid

Substitute =3 //Uses S_AdvancedDataGrid

class S_AdvancedDataGrid : UserControl , IDataGrid

Provides an implementation of IDataGrid interface via standard Windows Forms control, allowing to display and edit one or

more tables of data. Serves as a Excel-free substitute for AdvancedDataGrid control.

Normally you should not use this class directly, use C_AdvancedDataGrid instead.

Creates new S_AdvancedDataGrid control and fills it with default empty content

public bool ReadOnly

Specifies if user is allowed to edit data in this control

public void Destroy()

Releases resources associated with this control instance.

Members from IDataGrid interface:

void SetCellContent ( int sheet, int row, int col , object val );

object GetCellContent ( int sheet, int row, int col );

void SetSheetContent ( int sheet, DataTable t);

DataTable GetSheetContent ( int sheet, bool FirstRowHasHeaders , int n_col = 0, int n_row = 0);

void SetActiveSheet ( int index);

void DeleteSheet ( int index);

void AddSheet ( string name = «» );

List < XlSheet > GetSheets ( );

void SetSheetName ( int sheet, string name);

string GetSheetName ( int sheet);

int FindSheet ( string name);

See AdvancedDataGrid description for the information about the meaning of these methods.

6 комментариев:

can you please also add `DisplayExcel4Menus` option and if possible can you please provide me a code of that dll file so i can make some changes which i needed.

Could you update the download link? I cannot download the zip file with the link.

Download link is working perfect. Still you not able to download it , please check this link.https://marketplace.visualstudio.com/items?itemName=VadimTagil.WinFormsExcelLibrary

I can add content to an AdvancedDataGrid programmatically, but once I've done that, I also can't get the grid to respond to my keyboard.

I have an AdvancedDataGrid on a WinForm, along with three comboboxes and two buttons. When I run the app and the AdvancedDataGrid appears, I can do whatever I want in it manually. But once I click a button, or change a combo, or add content to the AdvancedDataGrid programmatically, the grid stops responding to the keyboard. I can't enter anything into it manually, and I can't use the cursor. Sometimes, I can click inside the formula bar, and then the problem goes away, but this only works sometimes.

Winforms таблица как в excel

Создание собственного элемента на примере таблицы на C# для Windows Form

В данной статье я опишу создания своих элементов для C# Windows Form.

Для примера буду создавать таблицу со всем функционалом DataGridView. Позже перейдем на свои элементы. Создание первого элемента разобьем на несколько уроков. В данном уроке произведем от рисовку таблицы, а также: создание столбцов, строк, ячеек.

Для написания будем использовать .Net FrameWork 4.7.x, среда разработки Visual Studio 2019.

В первую очередь создадим обычный проект Windows Form. Думаю не нужно это показывать. А уже потом создаем проект «Библиотека элементов управления Windows Form»(Назовем его CustomControl).

Далее у нас будет создан файл UserControl.cs. Удаляем его и создаем обычный класс TableCustoms.cs.Наш класс будет наследоваться от класса Control.

Далее в этом же файле создадим еще несколько классов, а именно:Column,Row,Cell. Рассмотрим каждый по отдельности. Начнем с Column:

Класс Cell(Для поддержки копирования добавляем интерфейс ICloneable):

Теперь настроим наш основной класс TableCustoms:

Для того, чтобы у нас были полосы прокрутки нужно использовать ScrollableControl, поэтому создадим класс PanelTable наследуем ScrollableControl и помещаем его на Control(в следующем уроке объясню почему создаем два разных контрола, а не используем сразу ScrollableControl):

После этого «Пересобираем проект» элемента и добавляем элемент на форму(в основном проекте):

Пошаговое руководство. Создание dataTable в конструкторе наборов данных

В этом пошаговом руководстве объясняется, как создать DataTable (без TableAdapter) с помощью конструктора наборов данных. Сведения о создании таблиц данных, включая TableAdapters, см. в разделе «Создание и настройка TableAdapters».

Создание приложения Windows Forms

В Visual Studio в меню Файл выберите пункты Создать>Проект.

Разверните visual C# или Visual Basic на панели слева, а затем выберите «Рабочий стол Windows«.

В средней области выберите тип проекта приложения Windows Forms .

Назовите проект DataTableWalkthrough и нажмите кнопку «ОК«.

Проект DataTableWalkthrough создается и добавляется в обозреватель решений.

Добавление нового набора данных в приложение

В меню Проект выберите команду Добавить новый элемент.

Откроется диалоговое окно Добавление нового элемента.

На панели слева выберите «Данные«, а затем выберите DataSet в средней области.

Выберите Добавить.

Visual Studio добавляет в проект файл с именем DataSet1.xsd и открывает его в конструкторе наборов данных.

Добавление новой dataTable в набор данных

Перетащите dataTable с вкладки DataSetпанели элементов в конструктор наборов данных.

Таблица с именем DataTable1 добавляется в набор данных.

Щелкните заголовок строки DataTable1 и переименуйте ее Music .

Добавление столбцов в Таблицу данных

Щелкните правой кнопкой мыши таблицу «Музыка «. Наведите указатель на пункт «Добавить» и нажмите кнопку «Столбец«.

Присвойт столбцу SongID имя.

В окне Свойства присвойте свойству DataType значение System.Int16.

Повторите этот процесс и добавьте следующие столбцы:

Установка первичного ключа для таблицы

Все таблицы данных должны иметь первичный ключ. Первичный ключ однозначно идентифицирует определенную запись в таблице данных.

Чтобы задать первичный ключ, щелкните правой кнопкой мыши столбец SongID и выберите команду «Задать первичный ключ«. Рядом со столбцом SongID появится значок клавиши.

Сохранение проекта

Чтобы сохранить проект DataTableWalkthrough , в меню «Файл » выберите «Сохранить все«.

Создать Excel в visual studio c#

Давайте научимся быстро и просто создавать и записывать файлы Excel с помощью visual studio c#. Наше самое простое приложение Windows Forms будет брать из текстбокса текст и заносить его в первую ячейку. Статья написана специально для Сергея =).

Начать необходимо с подключения библиотеки Microsoft.Office.Interop.Excel. Выглядеть это должно так:

Если у вас при открытии обозревателя решений – Ссылки – правая кнопка – Добавить ссылку – Сборки – в списке нет Microsoft.Office.Interop.Excel, то добавьте её через Nuget. Проект – управление пакетами NuGet – в строке поиска Excel:

Теперь создайте новый проект Windows Forms и на форму закиньте текстбокс и кнопку. На кнопки кликните два раза, откроется исходный код. В самом верху допишите следующее:

А в методе button1_Click замените так:

Вот, собственно говоря и все. Текст из текстбокса запишется в ячейку A1. Обратите внимание, что папка temp на диске уже должна существовать.

Дополнение. Прочитать первую ячейку

Это тоже просто:


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

Winforms таблица как в excel


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

DataGridView с фильтрацией как в Excel

Как мне сделать в WinForms Таблицу DataGridView с фильтрацией, чтобы нажимая правой кнопкой мыши по столбцу открывалось контекстное меню и предлагало выбрать или ввести параметры для фильтра. Прямо Как в Excel.

Vadim Ovchinnikov's user avatar

zerpico's user avatar

DataGridViewWithFilter

Есть вики и там же готовая dll-ка.

1) Подключаем DataGridViewWithFilter.dll;

2) DataGridViewWithFilter наследник DataGridView:

В DataGridViewWithFilter.dll четыре класса:

ColumnFilterClickedEventArg

Событие нажатия на кнопку фильтрации:

DataGridFilterHeader

Наследик DataGridViewColumnHeaderCell, тут мы добавим в заголовок кнопку фильтрации и привяжем событие:

FilterStatus

В таком виде будем хранить состояние фильтров:

DataGridViewWithFilter

Наследник DataGridView, тут и происходит вся магия:

DartAlex's user avatar

Здесь подробно описано как создать фильтр Drop-Down Filter List for a DataGridView. Но при больших данных (Более 20,000 уникальных записей) немного тормозит.

Добавить компонент контекстного меню. Создать в нем меню. Привязать компонент к DataGridView. Назначить действия при выборе соответствующих меню ��

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

PS: сама фильтрация происходит не в гриде, а в компоненте который поставляет данные для отображения в гриде (к примеру BindingSource, который привязан к таблице DataTable)

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

WinForms Excel Library (.NET Component)

  • .NET Framework 4.0+ or .NET Core 3.1+ (must be present on target machine)
  • MS Excel 2003+ (must be present on target machine)
  • Visual Studio 2010+ (for .NET Framework) or Visual Studio 2019+ (for .NET Core)

WinForms Excel Library allows to host MS Excel interface in Windows Forms application as a user control in order to display and edit one or more tables of data. The Excel application is started in different process, but the interface is fully integrated into your application as for any usual control. Basically, it works like DataGridView, but enables user to take advantage of various data processing and visualization capabilities of MS Excel, which might be useful in scientific, engineering or financial applications. The library interacts with Excel via Primary Interop Assemblies. Currently implemented functionality:

  • Filling data from files, DataTable objects or manually on cell-by-cell basis;
  • Displaying and editing one or several tables in your form in Excel GUI;
  • Getting data back as DataTable objects or getting the content of specific cells;
  • Saving data into file;
  • Adding charts;
  • Manipulating worksheets: adding, deleting, reordering, changing names, changing active sheet;
  • Showing/hiding Excel formula bar and status bar;
  • Direct access to Excel interoperability interfaces via Application object.

The library distribution package contains demo application project (Visual Studio 2010)

See documentation for more information.

System.Runtime.InteropServices.COMException (HRESULT 0x800A03EC) when trying to set cell content. This error happens when you try to programmatically set the content of the cell that user is currently editing (i.e., when user double clicked the cell and Excel entered edit mode on it, which displays input caret inside cell and enables user to type text). The only current workaround is to catch exception an ask user to exit from edit more by single-clicking on some other cell.

About

Library that allows to host MS Excel interface in Windows Forms application as a user control

Создать Excel в visual studio c#

Давайте научимся быстро и просто создавать и записывать файлы Excel с помощью visual studio c#. Наше самое простое приложение Windows Forms будет брать из текстбокса текст и заносить его в первую ячейку. Статья написана специально для Сергея =).

Начать необходимо с подключения библиотеки Microsoft.Office.Interop.Excel. Выглядеть это должно так:

Если у вас при открытии обозревателя решений – Ссылки – правая кнопка – Добавить ссылку – Сборки – в списке нет Microsoft.Office.Interop.Excel, то добавьте её через Nuget. Проект – управление пакетами NuGet – в строке поиска Excel:

Теперь создайте новый проект Windows Forms и на форму закиньте текстбокс и кнопку. На кнопки кликните два раза, откроется исходный код. В самом верху допишите следующее:

А в методе button1_Click замените так:

Вот, собственно говоря и все. Текст из текстбокса запишется в ячейку A1. Обратите внимание, что папка temp на диске уже должна существовать.

Дополнение. Прочитать первую ячейку

Это тоже просто:


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, си шарп, excel

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *