Use excel in delphi

Довольно распространенная задача в программировании – загрузка данных в проект из внешнего файла. В отличие от загрузки из обычного текстового файла, загрузка из Excel, как и любого другого специального файла или подключение к базе данных, требует отдельного механизма реализации.

В данной статье рассматривается один из наиболее удобных способов работы с подгружаемыми из Excel данными. Значения всех ячеек страницы Excel вносятся в двумерный массив типа Variant. Затем с этим массивом уже можно работать любыми привычными способами.

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

const
   xlCellTypeLastCell = $0000000B;
var
   ExcelApp, ExcelSheet: OLEVariant;
   MyMass: Variant;
   x, y: Integer;
begin
   // создание OLE-объекта Excel
   ExcelApp := CreateOleObject('Excel.Application');

   // открытие книги Excel
   ExcelApp.Workbooks.Open('C:my_excel.xls');

   // открытие листа книги
   ExcelSheet := ExcelApp.Workbooks[1].WorkSheets[1];

   // выделение последней задействованной ячейки на листе
   ExcelSheet.Cells.SpecialCells(xlCellTypeLastCell).Activate;

   // получение значений размера выбранного диапазона
   x := ExcelApp.ActiveCell.Row;
   y := ExcelApp.ActiveCell.Column;

   // присвоение массиву диапазона ячеек на листе
   MyMass := ExcelApp.Range['A1', ExcelApp.Cells.Item[X, Y]].Value;

   // закрытие книги и очистка переменных
   ExcelApp.Quit;
   ExcelApp := Unassigned;
   ExcelSheet := Unassigned;
end;

* Метод SpecialCells используется для выделения определенных ячеек на основании оценки их содержимого или других характеристик. Применяемое здесь значение параметра-константы xlCellTypeLastCell указывает методу выделить последнюю ячейку используемого диапазона, т.е. саму нижнюю правую ячейку в диапазоне, где введено хоть какое-то значение. Это позволяет копировать не все ячейки листа, а лишь диапазон, содержащий какие-либо данные.

Для использования команд работы с OLE-объектами для этого кода нужно добавить библиотеку:

uses
  ComObj;

После указанных операций данные введены в массив, из которого их можно перенести в компонент StringGrid или использовать их по своему усмотрению. Стоит заметить, что в полученном таким образом массиве данные индексы располагаются в следующем порядке: [номер строки, номер столбца]. Это видно из следующего примера вывода данных массива в компонент StringGrid.

// назначение размера StringGrid по размеру полученного диапазона ячеек
MyStringGrid.RowCount := x;
MyStringGrid.ColCount := y;

// заполнение таблицы StringGrid значениями массива
for x := 1 to MyStringGrid.ColCount do
  for y := 1 to MyStringGrid.RowCount do
      MyStringGrid.Cells[x-1, y-1] := MyMass[y, x];

Для работы с Excel в Delphi, первым делом нужно в Uses указать модуль ComObj.

procedure TForm1.Button1Click(Sender: TObject);

var

XL: Variant;

begin

XL := CreateOLEObject(‘Excel.Application’); // Создание OLE объекта

XL.WorkBooks.add; // Создание новой рабочей книги

XL.visible := true;

end;

Как обратиться к отдельным ячейкам листа Excel в Delphi

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Value:=’30’;

//Результатом является присвоение ячейке [1,1] первого листа значения 30. Также к ячейке

//текущего листа можно обратиться следующим образом:

XL.Cells[1, 1]:=’30’;

Как добавить формулу в ячейку листа Excel в Delphi

XL.WorkBooks[1].WorkSheets[1].Cells[3,3].Value := ‘=SUM(B1:B2)’;

Форматирование текста в ячейках Excel, производится с помощью свойств Font и Interior объекта Cell:

// Цвет заливки

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Interior.Color := clYellow;

// Цвет шрифта

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Font.Color := clRed;

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Font.Name := ‘Courier’;

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Font.Size := 16;

XL.WorkBooks[1].WorkSheets[1].Cells[1,1].Font.Bold := True;

Работа с прямоугольными областями ячеек, с помощью объекта Range:

XL.WorkBooks[1].WorkSheets[1].Range[‘A1:C5’].Value := ‘Blue text’;

XL.WorkBooks[1].WorkSheets[1].Range[‘A1:C5’].Font.Color := clBlue;

//В результате в области A1:C5 все ячейки заполняются текстом ‘Blue text’.

Как выделить группу (область) ячеек Excel в Delphi

XL.Range[‘A1:C10’].Select;

Как установить объединение ячеек, перенос по словам, и горизонтальное или вертикальное выравнивание Excel в Delphi

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

//Выделяем группу (область) ячеек

XL.Range[‘A1:C10’].Select;

// объединение ячеек

XL.Selection.MergeCells:=True;

// перенос по словам

XL.Selection.WrapText:=True;

// горизонтальное выравнивание

XL.Selection.HorizontalAlignment:=3;

//вериткальное выравнивание

XL.Selection.VerticalAlignment:=1;

//Возможны следующие значения:

//1 — выравнивание по умолчанию,

//2 — выравнивание слева,

//3 — выравнивание по центру,

//4 — выравнивание справа.

Как задать границы ячеек Excel в Delphi

XL.Selection.Borders.LineStyle:=1;

// значение может быть установлено от 1 до 10

Как выровнять столбцы Excel по ширине, в зависимости от содержания

XL.selection.Columns.AutoFit;

Как удалить столбец Excel в Delphi

Как задать формат ячеек Excel в Delphi

XL.columns[1].NumberFormat := ‘@’; // текстовый формат

XL.columns[1].NumberFormat := ‘m/d/yyyy’; //  формат дата

XL.columns[1].NumberFormat = ‘0.00%’ // формат процентный

XL.columns[1].NumberFormat = ‘h:mm;@’// формат время


This step-by-step guide describes how to connect to Microsoft Excel, retrieve sheet data, and enable editing of the data using the DBGrid. You’ll also find a list of the most common errors that might appear in the process, plus how to deal with them.

What’s Covered Below:

  • Methods for transferring data between Excel and Delphi. How to connect to Excel with ADO (ActiveX Data Objects) and Delphi.
  • Creating an Excel spreadsheet editor using Delphi and ADO
  • Retrieving the data from Excel. How to reference a table (or range) in an Excel workbook.
  • A discussion on Excel field (column) types
  • How to modify Excel sheets: edit, add and delete rows.
  • Transferring data from a Delphi application to Excel. How to create a worksheet and fill it with custom data from an MS Access database.

How to Connect to Microsoft Excel

Microsoft Excel is a powerful spreadsheet calculator and data analysis tool. Since rows and columns of an Excel worksheet closely relate to the rows and columns of a database table, many developers find it appropriate to transport their data into an Excel workbook for analysis purposes; and retrieve data back to the application afterwards.

The most commonly used approach to data exchange between your application and Excel is Automation. Automation provides a way to read Excel data using the Excel Object Model to dive into the worksheet, extract its data, and display it inside a grid-like component, namely DBGrid or StringGrid.

Automation gives you the greatest flexibility for locating the data in the workbook as well as the ability to format the worksheet and make various settings at run time.

To transfer your data to and from Excel without Automation, you can use other methods such as:

  • Write data into a comma-delimited text file, and let Excel parse the file into cells
  • Transfer data using DDE (Dynamic Data Exchange)
  • Transfer your data to and from a worksheet using ADO

Data Transfer Using ADO

Since Excel is JET OLE DB compliant, you can connect to it with Delphi using ADO (dbGO or AdoExpress) and then retrieve the worksheet’s data into an ADO dataset by issuing an SQL query (just like you would open a dataset against any database table).

In this way, all the methods and features of the ADODataset object are available to process the Excel data. In other words, using the ADO components let you build an application that can use an Excel workbook as the database. Another important fact is that Excel is an out-of-process ActiveX server. ADO runs in-process and saves the overhead of costly out-of-process calls.

When you connect to Excel using ADO, you can only exchange raw data to and from a workbook. An ADO connection cannot be used for sheet formatting or implementing formulas to cells. However, if you transfer your data to a worksheet that is pre-formatted, the format is maintained. After the data is inserted from your application to Excel, you can carry out any conditional formatting using a (pre-recorded) macro in the worksheet.

You can connect to Excel using ADO with the two OLE DB Providers that are a part of MDAC: Microsoft Jet OLE DB Provider or Microsoft OLE DB Provider for ODBC Drivers. We’ll focus on Jet OLE DB Provider, which can be used to access data in Excel workbooks through installable Indexed Sequential Access Method (ISAM) drivers.

Tip: See the Beginners Course to Delphi ADO Database Programming if you’re new to ADO.

The ConnectionString Magic

The ConnectionString property tells ADO how to connect to the datasource. The value used for ConnectionString consists of one or more arguments ADO uses to establish the connection.

In Delphi, the TADOConnection component encapsulates the ADO connection object; it can be shared by multiple ADO dataset (TADOTable, TADOQuery, etc.) components through their Connection properties.

In order to connect to Excel, a valid connection string involves only two additional pieces of information — the full path to the workbook and the Excel file version.

A legitimate connection string could look like this:

ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:MyWorkBooksmyDataBook.xls;Extended Properties=Excel 8.0;';

When connecting to an external database format supported by the Jet, the extended properties for the connection needs to be set. In our case, when connecting to an Excel «database,» extended properties are used to set the Excel file version. 

For an Excel95 workbook, this value is «Excel 5.0» (without the quotes); use «Excel 8.0» for Excel 97, Excel 2000, Excel 2002, and ExcelXP.

Important: You must use the Jet 4.0 Provider since Jet 3.5 does not support the ISAM drivers. If you set the Jet Provider to version 3.5, you’ll receive the «Couldn’t find installable ISAM» error.

Another Jet extended property is «HDR=». «HDR=Yes» means that there is a header row in the range, so the Jet will not include the first row of the selection into the dataset. If «HDR=No» is specified, then the provider will include the first row of the range (or named range) into the dataset.

The first row in a range is considered to be the header row by default («HDR=Yes»). Therefore, if you have column heading, you do not need to specify this value. If you do not have column headings, you need to specify «HDR=No».

Now that you’re all set, this is the part where things become interesting since we’re now ready for some code. Let’s see how to create a simple Excel Spreadsheet editor using Delphi and ADO.

Note: You should proceed even if you lack knowledge on ADO and Jet programming. As you’ll see, editing an Excel workbook is as simple as editing data from any standard database.

Здравствуйте, в этой статье я расскажу Вам, как использовать в своем приложении (программе) на Delphi БД в виде MS Excel. Да да именно MS Excel. Тут ничего сложного нету. Для начала давайте заполним наш лист в MS Excel. Первая строка в каждом столбце всегда будет брать наше приложение как название столбцов, то есть оно не берет название столбцов такое — A, B, C и так далее. Так что в первсой строке столбца А и столбца B я написал ФИО и Оценка соответственно для каждого столбца. Это и будут наши заголовки, затем ниже я заполнил данные, которые будут в моей БД, ну это фамилии и оценки сами напиши. Так БД у нас готова. Теперь создадим к ней подключение. создается подключение похоже как и в MS Access, так что тут ничего сложного нету. На форме у нас старые компоненты это

  • TDBGrid
  • TADOQuery
  • TADOConnection
  • TDataSource

Как связывать эти компоненты я расскажу быстро, так как это уже было сказано мною.

  • TADOQuery c TADOConnection в свойстве — Connection
  • TDataSource с TADOQuery в свойстве DataSet
  • TDBGrid c TDataSource в свойстве DataSource

В TADOConnection установим свойство LongPromt в False. Вроде бы небольшую настройку сделали. Теперь приходим к непосредственному подключени. В свойстве TADOConnection ConnectionString нажимаем на кнопку ««, далее у нас появляется окно вида

Нажимаем на кнопку «Build…» и появляется следующее окно

В данном окне выбираем следующего провайдера: Microsoft OLE DB Provider for ODBC Drivers и нажимаем кнопку «Далее>>» и видем следующее окно

В этом окне сразу ставим указатель на «Использовать строку подключения» и нажимаем на кнопку «Сборка«, после чего появляется окно

В этом окне переходим на вкладку Источник данных компьютера, в появившемся списке выбираем — Файлы Excel, а точнее жмем левой кнопкой мыши по этой сроке двойным щелчком и в появившемся окне указываем путь к нашей Excel-книги, которую мы создавали. После этого нажимаем на пноку «Ok«. Все подключение у нас готово. Хочу добавить еще, если у Вас файл Excel, где ваша таблица находится лежит в одном каталоге с программой, то в свойстве компонента TADOConnection ConnectionString будет прописан путь к Вашему Excel-файлу, стерите путь, а оставьте просто имя Вашего Excel файла с расширением, а в свойстве DefaultDataBase этого же компонента, напишите имя вашего Excel-файла с расширением. Тогда при запуске вашего приложения, не будет возникать ошибок с неправильно заданым путем к вашей БД. Далее в TDBGrid нажмем по нему двойным щелчком и в появившемся окне создаим 2 строки, это наши столбцы будут. А создаются они путем нжатия в данном окне на кнопку «Add New (Ins)«. Далее выделив кажду строку в свойстве FieldName для первой строки напишем — ФИО, так как в Excel-файле я именно так написал в первую строку название столбца (для ячейки A1 я так написал), а выделив вторую строку, что создали в TDBGrid, в свойстве FieldName напишем — Оценка, так как именно я такое название столбца написал (в ячейке А2 я так написал). Все теперь нам можно активировать наши данные. Для этого на событие главной формы — OnCreate напишем следующее

procedure TForm1.FormCreate(Sender: TObject);
begin
try
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('SELECT * FROM [Лист1$]');
ADOQuery1.Active:=True;
except
on e:Exception do
end;
end;

Как видите все тот же запрос, только вместо имя таблица, как у нас было в MS Access мы указываем имя листа нашего в Excel, заключив его в квадратные скобки и поставив в конце знак $. Как видите ничего сложного нету. В следующей статье про БД MS Excel я расскажу как вставлять данные, редактировать и так далее.

Понравилась статья? Поделить с друзьями:
  • Unit 20 weather and the environment word formation
  • Unit 18 education and learning word formation
  • Use excel for database
  • Unit 15 grammar choose the correct word or phrase
  • Use excel for data analysis