Cxgrid to excel delphi

Exports content of a data grid control to a file in Microsoft Excel® binary format (XLS).

Declaration

procedure ExportGridToExcel(const AFileName: string; AGrid: TcxGrid; AExpand: Boolean = True; ASaveAll: Boolean = True; AUseNativeFormat: Boolean = True; const AFileExt: string = 'xls'; AHandler: TObject = nil);

Parameters

Name Type Description
AFileName string

The full path to the resulting XLS file. You can omit the file name extension because it is automatically updated from the AFileExt parameter value.

AGrid TcxGrid

The source data grid control.

AExpand Boolean

Optional. If True, the procedure exports all rows, including the rows hidden within collapsed group rows and master rows. If False, the procedure exports only visible rows.

ASaveAll Boolean

Optional. If True, the procedure exports all or visible rows, depending on the AExpand parameter value. If False, the procedure exports only selected rows. In grid mode, the ASaveAll parameter value is ignored.

AUseNativeFormat Boolean

Optional. If True, the procedure attempts to convert display text of a grid item’s cells to their underlying data format (that is, Currency, Date, Time, Numeric, etc.) The table below lists supported in-place editors and the corresponding data formats. If False, the procedure exports display text as string values.

AFileExt string

Optional. Specifies the file name extension for the resulting XLS file. This parameter value always replaces the file name extension passed as a part of the AFileName parameter value.

AHandler TObject

Optional. Specifies a handler object that should implement the IcxExportBeforeSave and/or IcxExportProgress interfaces to allow you to perform specific actions before an export operation and track its progress. Refer to the following topic for detailed information on how to create and use handler objects: How to: Track Data Export Progress.

If you pass True as the AUseNativeFormat parameter, the ExportGridToExcel procedure attempts to convert display text of a grid item’s cells to their underlying data format (Currency, Date, Time, Numeric, etc.) If you assign an in-place editor to a cell, the export procedure selects the data format according to the following table:

In-place Editor Data Format
TcxCurrencyEdit Currency
TcxMaskEdit or TcxCalcEdit Currency, if the assigned editor is bound to a dataset field whose values are formatted as currency values (TAggregateField.Currency, TBCDField.Currency, TFloatField.Currency, or TFMTBCDField.Currency). Otherwise, the data format is Number.
TcxDateEdit Date
TcxTimeEdit Time
TcxSpinEdit Number

If any other editor is assigned to a cell, the ExportGridToExcel procedure exports its display text regardless of the AUseNativeFormat parameter value. If it is impossible to convert display text to the target data type for any reason, the display text is exported as a string.

Note

The listed data formats are used for value conversion only. They do not correspond to cell number formats found in Microsoft Excel®. Populated cells have the General format.

Summary values use the same data type as cell values against which these summaries are calculated if the following conditions are met for the corresponding summary items:

  • An empty string is assigned to a summary item’s Format property.
  • An OnGetText event handler is not assigned to a summary item.

Example

Source Data Grid Example

The following code example exports grid content to a file in XLS format with expanded detail pages:

  • Delphi
  • C++
  ExportGridToExcel('Employees.xls', cxGrid1, True);

Exported Data in XLS Format

See Also

Содержание

  1. Русские Блоги
  2. Delphi экспортирует данные из CxGrid в Excel
  3. Интеллектуальная рекомендация
  4. Проверка полномочий на основе JWT и фактические боевые учения
  5. [Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов
  6. Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)
  7. [Серия исходного кода Java] строка (2) Проблема нового, а не новой
  8. 05-Vue News Mobile Project
  9. Вам также может понравиться
  10. 1008 Рассматривая задача Element Element Cycle (20 баллов)
  11. Linux centos7 виртуальная машина установить Docker (5) —. Netcore
  12. Разработать интерфейс мониторинга состояния здоровья
  13. [Реабилитация] #C Language Array Joseph Проблема
  14. ExportGridToExcel(string,TcxGrid,Boolean,Boolean,Boolean,string,TObject) Method
  15. Declaration
  16. Parameters
  17. Remarks
  18. Example
  19. ExportGridToXLSX(string,TcxGrid,Boolean,Boolean,Boolean,string,TObject) Method
  20. Declaration
  21. Parameters
  22. Remarks
  23. Example
  24. Как вставить данные из Excel в cxGrid
  25. 2 ответы
  26. Как вставить данные из Excel в cxGrid
  27. 2 ответы

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

Delphi экспортирует данные из CxGrid в Excel

Используйте метод, поставляемый с CxGrid

Достоинства: простые параметры

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

Проверка полномочий на основе JWT и фактические боевые учения

Предисловие: Большинство систем, за исключением большинства финансовых систем, требуют строгой системы безопасности (такой как shiro), общие требования к безопасности системы не очень высоки, требуетс.

[Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов

1. Реализуйте переднюю и заднюю часть приложения Цель:Чтобы снять риск захвата интерфейса Android, сообщите пользователям, что приложение работает в фоновом режиме. Обычно нажимает клавишу Home, чтобы.

Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)

Эта статья основана на USB Wireless Network Card (RTL8188CUS Chip), приобретенной на определенном востоке, чтобы создать беспроводные горячие точки. Первоначально я хотел сделать один сценарий. Просто.

[Серия исходного кода Java] строка (2) Проблема нового, а не новой

Серия строк: 【Серия исходного кода Java】 строка (1) под анализом базовой структуры [Серия исходного кода Java] строка (2) Проблема нового, а не новой [Серия исходного кода Java] Строка (3) Общий анали.

05-Vue News Mobile Project

1 Javascri не добавляет при добавлении толстой кишки При получении и изменении атрибутов реквизит плюс this. $router.push( ) 2 Axios Установка и использование Цитата в main.js 2.1axios, чтобы отправит.

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

1008 Рассматривая задача Element Element Cycle (20 баллов)

Массив A содержит n (> 0) целое число, не позволяя использовать дополнительные массивы, чтобы повернуть каждое целое число в положение правого m (≥0), данные в (A 0) A1 ⋯ A N-1) (An-M ⋯ A N-1 A .

Linux centos7 виртуальная машина установить Docker (5) —. Netcore

Текущая версия: версия Docker (например, Docker 17.03.2) .netcore версия 3.1 1 Постройте зеркало 2 запустить зеркало 3 Доступ Введите контейнер Nginx: Посещение в контейнере Выйдите из контейнера, что.

Разработать интерфейс мониторинга состояния здоровья

1. Требование Интерфейс должен содержать логическую обработку и чтение базы данных. 2. Реализация 1) Разработать доступ к интерфейсу к базе данных, успешный доступ, код статуса возврата 200, ненормаль.

[Реабилитация] #C Language Array Joseph Проблема

Я не двигал код в течение года. Теперь мой мозг не хорош, я использовал глупость, чтобы решить проблему Йозефа кольца. Написание здесь является запись, которая спасает свой собственный беспорядок. Воп.

Источник

ExportGridToExcel(string,TcxGrid,Boolean,Boolean,Boolean,string,TObject) Method

Exports content of a data grid control to a file in Microsoft Excel® binary format (XLS).

Declaration

Parameters

The full path to the resulting XLS file. You can omit the file name extension because it is automatically updated from the AFileExt parameter value.

The source data grid control.

Optional. If True , the procedure exports all rows, including the rows hidden within collapsed group rows and master rows. If False , the procedure exports only visible rows.

Optional. If True , the procedure exports all or visible rows, depending on the AExpand parameter value. If False , the procedure exports only selected rows. In grid mode, the ASaveAll parameter value is ignored.

Optional. If True , the procedure attempts to convert display text of a grid item’s cells to their underlying data format (that is, Currency, Date, Time, Numeric, etc.) The table below lists supported in-place editors and the corresponding data formats. If False , the procedure exports display text as string values.

Optional. Specifies the file name extension for the resulting XLS file. This parameter value always replaces the file name extension passed as a part of the AFileName parameter value.

Optional. Specifies a handler object that should implement the IcxExportBeforeSave and/or IcxExportProgress interfaces to allow you to perform specific actions before an export operation and track its progress. Refer to the following topic for detailed information on how to create and use handler objects: How to: Track Data Export Progress.

If you pass True as the AUseNativeFormat parameter, the ExportGridToExcel procedure attempts to convert display text of a grid item’s cells to their underlying data format (Currency, Date, Time, Numeric, etc.) If you assign an in-place editor to a cell, the export procedure selects the data format according to the following table:

Name Type Description
AFileName string
In-place Editor Data Format
TcxCurrencyEdit Currency
TcxMaskEdit or TcxCalcEdit Currency, if the assigned editor is bound to a dataset field whose values are formatted as currency values (TAggregateField.Currency, TBCDField.Currency, TFloatField.Currency, or TFMTBCDField.Currency). Otherwise, the data format is Number.
TcxDateEdit Date
TcxTimeEdit Time
TcxSpinEdit Number

If any other editor is assigned to a cell, the ExportGridToExcel procedure exports its display text regardless of the AUseNativeFormat parameter value. If it is impossible to convert display text to the target data type for any reason, the display text is exported as a string.

The listed data formats are used for value conversion only. They do not correspond to cell number formats found in Microsoft Excel®. Populated cells have the General format.

Summary values use the same data type as cell values against which these summaries are calculated if the following conditions are met for the corresponding summary items:

  • An empty string is assigned to a summary item’s Format property.
  • An OnGetText event handler is not assigned to a summary item.

Example

The following code example exports grid content to a file in XLS format with expanded detail pages:

Источник

ExportGridToXLSX(string,TcxGrid,Boolean,Boolean,Boolean,string,TObject) Method

Exports the currently active root level’s content to a file in Office Open XML spreadsheet format (XLSX).

Declaration

Parameters

The full path to the resulting text file. You can omit the file name extension because it is automatically updated from the AFileExt parameter value.

The source data grid control.

Optional. If True , the procedure exports all rows, including the rows hidden within collapsed group rows and master rows. If False , the procedure exports only visible rows.

Optional. If True , the procedure exports all or visible rows, depending on the AExpand parameter value. If False , the procedure exports only selected rows. In grid mode, the ASaveAll parameter value is ignored.

Optional. If True , the procedure attempts to convert display text of a grid item’s cells to their underlying data format (that is, Currency, Date, Time, Numeric, etc.) The table below lists supported in-place editors and the corresponding data formats. If False , the procedure exports display text as string values.

Optional. Specifies the file name extension for the resulting Office Open XML file. This parameter value always replaces the file name extension passed as a part of the AFileName parameter value.

Optional. Specifies a handler object that should implement the IcxExportBeforeSave and/or IcxExportProgress interfaces to allow you to perform specific actions before an export operation and track its progress. Refer to the following topic for detailed information on how to create and use handler objects: How to: Track Data Export Progress.

If you pass True as the AUseNativeFormat parameter, the ExportGridToXLSX procedure attempts to convert display text of a grid item’s cells to their underlying data format (Currency, Date, Time, Numeric, etc.) If you assign an in-place editor to a cell, the export procedure selects the data format according to the following table:

Name Type Description
AFileName string
In-place Editor Data Format
TcxCurrencyEdit Currency
TcxMaskEdit or TcxCalcEdit Currency, if the assigned editor is bound to a dataset field whose values are formatted as currency values (TAggregateField.Currency, TBCDField.Currency, TFloatField.Currency, or TFMTBCDField.Currency). Otherwise, the data format is Number.
TcxDateEdit Date
TcxTimeEdit Time
TcxSpinEdit Number

If any other editor is assigned to a cell, the ExportGridToXLSX procedure exports its display text regardless of the AUseNativeFormat parameter value. If it is impossible to convert display text to the target data type for any reason, the display text is exported as a string.

The listed data formats are used for value conversion only. They do not correspond to cell number formats found in Microsoft Excel®. Populated cells have the General format.

Summary values use the same data type as cell values against which these summaries are calculated if the following conditions are met for the corresponding summary items:

  • An empty string is assigned to a summary item’s Format property.
  • An OnGetText event handler is not assigned to a summary item.

Example

The following code example exports grid content to a file in XLSX format with expanded detail pages:

Источник

Как вставить данные из Excel в cxGrid

У меня есть приложение Delphi, использующее DevExpress cxGrid (которое подключено к базе данных).

Мне нужно иметь возможность копировать и вставлять данные из Excel в сетку.

Это возможно? Если да, то как это сделать, какие дополнительные компоненты мне нужны?

2 ответы

Проверьте формат с помощью Clipboard.HasFormat(CF_TEXT) .

Извлеките текст с помощью Clipboard.AsText .

Разделить на ряды с StringList.Text := Clipboard.AsText . Каждый элемент в списке строк теперь является строкой из буфера обмена.

Разделите каждую строку на отдельные ячейки с помощью функции разделения:

ответ дан 05 дек ’10, 10:12

это может быть достигнуто проще И более элегантно, используя TStringList и назначив символ-разделитель, затем установите длину массива равным счетчику переменной TStringList И, чем просто скопируйте каждый элемент в соответствующий строковый элемент в массиве . или вы могли просто получить доступ к каждому элементу в списке строк — user497849

@Dorin Duminica Excel — данные в формате 2D, разве ваше предложение не превратит их в одномерный массив? — Дэвид Хеффернан

@Dorin Duminica Я подозреваю, что вы ссылаетесь на свойство Delimiter, но это просто не сработает в целом — Дэвид Хеффернан

Вы можете обнаружить, что эта функция разделения прерывается, когда ваши ячейки содержат символы табуляции, потому что Excel придется как-то их экранировать (возможно, с кавычками вокруг ячейки). Но вы должны суметь справиться с этим достаточно легко, если это станет проблемой. — Дэвид Хеффернан

@Dorin Duminica да, действительно, есть, хотя это что-то вроде несеквитера — Дэвид Хеффернан

Вы можете проверить содержимое буфера обмена после копирования содержимого из приложения Excel. а затем с помощью сочетания клавиш CTRL + V вы анализируете содержимое буфера обмена и устанавливаете данные в соответствующие ячейки.

ответ дан 05 дек ’10, 09:12

Вероятно, самый простой формат — это извлечь его как текст и вставить в список строк с помощью свойства Text. Каждый элемент в списке будет представлять собой целую строку, которую затем можно разделить на ячейки по границам столбцов, отмеченные символами табуляции ht. — Дэвид Хеффернан

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками delphi excel devexpress copy-paste quantumgrid or задайте свой вопрос.

Источник

Как вставить данные из Excel в cxGrid

У меня есть приложение Delphi, использующее DevExpress cxGrid (которое подключено к базе данных).

Мне нужно иметь возможность копировать и вставлять данные из Excel в сетку.

Это возможно? Если да, то как это сделать, какие дополнительные компоненты мне нужны?

2 ответы

Проверьте формат с помощью Clipboard.HasFormat(CF_TEXT) .

Извлеките текст с помощью Clipboard.AsText .

Разделить на ряды с StringList.Text := Clipboard.AsText . Каждый элемент в списке строк теперь является строкой из буфера обмена.

Разделите каждую строку на отдельные ячейки с помощью функции разделения:

ответ дан 05 дек ’10, 10:12

это может быть достигнуто проще И более элегантно, используя TStringList и назначив символ-разделитель, затем установите длину массива равным счетчику переменной TStringList И, чем просто скопируйте каждый элемент в соответствующий строковый элемент в массиве . или вы могли просто получить доступ к каждому элементу в списке строк — user497849

@Dorin Duminica Excel — данные в формате 2D, разве ваше предложение не превратит их в одномерный массив? — Дэвид Хеффернан

@Dorin Duminica Я подозреваю, что вы ссылаетесь на свойство Delimiter, но это просто не сработает в целом — Дэвид Хеффернан

Вы можете обнаружить, что эта функция разделения прерывается, когда ваши ячейки содержат символы табуляции, потому что Excel придется как-то их экранировать (возможно, с кавычками вокруг ячейки). Но вы должны суметь справиться с этим достаточно легко, если это станет проблемой. — Дэвид Хеффернан

@Dorin Duminica да, действительно, есть, хотя это что-то вроде несеквитера — Дэвид Хеффернан

Вы можете проверить содержимое буфера обмена после копирования содержимого из приложения Excel. а затем с помощью сочетания клавиш CTRL + V вы анализируете содержимое буфера обмена и устанавливаете данные в соответствующие ячейки.

ответ дан 05 дек ’10, 09:12

Вероятно, самый простой формат — это извлечь его как текст и вставить в список строк с помощью свойства Text. Каждый элемент в списке будет представлять собой целую строку, которую затем можно разделить на ячейки по границам столбцов, отмеченные символами табуляции ht. — Дэвид Хеффернан

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками delphi excel devexpress copy-paste quantumgrid or задайте свой вопрос.

Источник

procedure T supplier management .dxbarlargebutton3clCK (Sender: Tobject);
var
  SaveDialog: TSaveDialog;  
  path: string; // path information
     Excelapp: variant; // Variation variables
begin
  SaveDialog := TSaveDialog.Create(nil);
  path := '';
  try
    with SaveDialog do
    begin
      FileName := 'Supplier information' + FormatDateTime('YYYYMMDD', Now ()); // default file name
      Filter := '*.xls|*.xls|*.xlsx|*.xlsx|';
      if Execute then
      begin
        case SaveDialog.FilterIndex of
          1:
            ExportGridToExcel(SaveDialog.FileName, Supplier substrate 1.cxgrid4, true, true, true, 'xls');
          2:
            ExportGridToXLSX(SaveDialog.FileName, Supplier substrate 1.cxgrid4, true, true, true, 'xlsx');  //2007
        end;
      end;
    end;
  finally
    path := SaveDialog.FileName;
    SaveDialog.Free;
  end;

  if path <> '' then     //open a file
  begin
    ExcelAPP := CreateOleObject('Excel.Application'); // Create an excel object
    ExcelAPP.Visible := false;
         Excelapp.Workbooks.open (PATH); // Use Excel's method to open the file
    ExcelAPP.WorkSheets[1] .Activate; // The file operation, here is no different from the VBA operation anymore
    ExcelAPP.Visible :=  True; // Show out
  end;
end;

Используйте метод, поставляемый с CxGrid

Достоинства: простые параметры

uses cxExportGrid4Link;
procedure TFrm_func.CxGridToExcel(AcxGrid: TcxGrid);
var
 SaveDialog: TSaveDialog;
begin
 SaveDialog := TSaveDialog.Create(nil);
 with SaveDialog do
 begin
   Filter := '*.xls|*.xls';
   if Execute then
     ExportGrid4ToExcel(SaveDialog.FileName, AcxGrid, true, true, true, 'xls');
 end;
 SaveDialog.Free;
end;

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

Помимо восстановления Oracle длинного поля

Система обслуживания клиентов из-за неправильной работы удалила данные и сразу же rman восстановила данные в тестовой среде, а затем постепенно восстановила данные в производственной среде в соответст…

python — распознавать текст в картинках

Эта статья в основном относится кОбработка изображений Python для идентификации текста в изображенияхЭта статья, есть некоторые отклонения в процессе реализации, настоящим записью. Поскольку я не уста…

722.Remove Comments

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code strin…

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

Создайте ресурсы изображения из слоя (группа)

В файле PSD, если вы измените имя группы или группы слоя, вы можете автоматически генерировать ресурсы изображения в форматах JPEG, PNG или GIF и указать качество и размер. Включить метод Меню: Ресурс…

Искать имя файла файла под Linux

1. Поиск команды файла. Команда 1, когда используется для поиска абсолютного пути исполняемого файла. Команда 2-х годов, найдите файл, связанный с именем файла, формат, где [-BMS] [имя файла]. Имя]. П…

Принцип динамического прокси-JDK Proxy

В прошлый раз, когда мы объясняли реализацию динамического прокси cglib, сегодня мы рассмотрим принцип реализации прокси JDK. Отображение текущей метки времени до и после выполнения метода класса Subj…

Мин Чэнь: сегодняшняя информация

25 марта: ночная важная новость 1. Режим продаж Smirect Playpad Pointpad Proop — это шаблон лотереи лотереи. BNB увеличился на 13% за последние 24 часа. 2. Бывший министр финансов США Джейкоб Л заявил…

#excel #delphi #devexpress #vcl #tcxgrid

#excel #delphi #девэкспресс #vcl #tcxgrid

Вопрос:

У меня есть задача экспортировать cxGrid с изображениями из разных форм приложения Delphi. Теперь для экспорта изображения я использую буфер обмена следующим образом Clipboard.Assign(Picture) , затем я выбираю столбец и использую метод Excel.Selection.PasteSpecial для вставки изображения из буфера обмена. Но, похоже, этот способ не такой быстрый, как мне нужно. И, может быть, вы знаете другие способы экспорта изображения из приложения Delphi в Excel?

Комментарии:

1. Помимо буфера обмена, я вижу только одну другую возможность: сохранить изображение на диске и заставить Excel загрузить файл оттуда. Вероятно, это будет медленнее, потому что буфер обмена — это процесс в памяти, в то время как использование диска включает … диск, который всегда работает медленнее.

Понравилась статья? Поделить с друзьями:
  • Cvs как перевести excel
  • Cvs в excel абракадабра
  • Cvs format in word
  • Cvp анализ пример в excel
  • Cvc word что это