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

Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, си шарп, excel
Как отобразить таблицу exel в WinForm?
как перебрать таблицу exel что б можно показать ее например в listView или DataGridView?
![]()
Рекомендую использовать сторонние библиотеки, поддерживающие формат xlsx. Использовать Interop не рекомендую (в основе его лежит медленный COM и требуется наличие MS Office).
Использовал библиотеку EPPlus. Она бесплатна для некоммерческого использования. Позволяет читать ячейки, а можно загрузить диапазон ячеек в DataTable.
Добавьте nuget пакет EPPlus в ваше приложение, а далее используйте вышеуказанные примеры кода для чтения Excel.
![]()
Считай все ячейки из документа и поставь как контент датагридвью.
Если ты умеешь пользоваться 2хмерным масивом и датагридвьюхой — у тебя проблем не возникнет в принципе, если воспользуешся вот этим ответом:
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
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
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.