Lazarus как открыть excel

Microsoft-Excel-Featured-Image

Для работы с Excel файлами без установленного на ПК MS Office, можно использовать компонент FPSpreadsheet. Он работает как на windows(WinCE, XP и выше), так и на Linux.

Для начала скачайте его: https://sourceforge.net/projects/lazarus-ccr/files/FPSpreadsheet/

1.Распаковываем архив в папку с Lazaruscomponents(Например C:lazaruscomponents)

2.Открываем Lazarus

3.Жмем: Пакет-> Открыть файл пакета (.lpk)

1

4.Открываем папку, куда распаковали компонент.

2

5.Выбираем файл laz_fpspreadsheet.lpk

6.Жмем Компилировать.

3

7. Далее снова выбираем в меню Пакет-> Открыть файл пакета (.lpk) и открываем уже laz_fpspreadsheet_visual.lpk

4

8. Жмем Установить. В первом окне нажимаем Да, подтверждая установку компонента. Во втором окне так же жмем Да, чтобы пересобрать Lazarus.

5

Все компонент установлен.

Ниже приведу маленький код, в котором мы записываем данные в таблицу.

uses ...  fpspreadsheet, fpsTypes, xlsbiff8, fpsutils;
procedure ExcelWrite; 
var
   MyWorkbook: TsWorkbook;
   MyWorksheet: TsWorksheet;
begin
   MyWorkbook := TsWorkbook.Create;
   MyWorkbook.ReadFromFile('Путь к файлу.xls', sfExcel8);      //Открываем таблицу
   MyWorksheet := MyWorkbook.GetFirstWorksheet;                //Выбираем рабочий лист, 
                                                               //в данном случае первый
   MyWorksheet.WriteUTF8Text(Строка,Колонка,'Данные');         //Записываем данные в ячейку

   MyWorkbook.WriteToFile('Путь к файлу.xls', sfExcel8, True); //Сохраняем Таблицу
   MyWorkbook.Free;
end;

Более подробно о возможностях данного компонента вы сможете прочитать на сайте http://wiki.lazarus.freepascal.org/FPSpreadsheet

Windows logo - 2012.svg







Deutsch (de)
English (en)

español (es)


français (fr)


italiano (it)







русский (ru)






中文(中国大陆)‎ (zh_CN)


The ability to interact with Office software and generate spreadsheets, text documents and presentations from code can be invaluable in the office, and save a lot of time otherwise spent on repetitive tasks.

One example of this is the creation of applications that can read files in an arbitrary format and output an Excel file, a task that can be done much more efficiently with code than manually.

Using the OpenOffice UNO Bridge

OpenOffice has language bindings for C++, Java, JavaScript and Python. On Windows, OpenOffice can also be manipulated in Pascal via COM Automation (see below), but there is currently no easy way of using OpenOffice’s UNO (Universal Network Objects) from Pascal on OS X and Linux. If you’re interested in developing an OO «bridge» for Pascal, please refer to these links for more information (caution: these links are quite techie in true Sun fashion):

api.openoffice.org

About Bridges

Using COM Automation to interact with OpenOffice and Microsoft Office

Automation is unique to Windows so the following two examples won’t work on OS X or Linux. For those platforms, please refer to Making do without Windows COM Automation. If you only need to create and/or view a word processing document from your program, take a look at the XDev Toolkit.

OpenOffice/LibreOffice on Windows

Here’s a simple example of how to open a document with your program using the OpenOffice Automation server. Note that this works only on Windows.

program TestOO;

{$IFDEF FPC}
 {$MODE Delphi}
{$ELSE}
 {$APPTYPE CONSOLE}
{$ENDIF} 

uses
  SysUtils, Variants, ComObj;

const
  ServerName = 'com.sun.star.ServiceManager';
var          
  Server     : Variant;
  Desktop    : Variant;
  LoadParams : Variant;
  Document   : Variant;
  TextCursor : Variant;
begin
  if Assigned(InitProc) then
    TProcedure(InitProc);

  try
    Server := CreateOleObject(ServerName);
  except
    WriteLn('Unable to start OO.');
    Exit;
  end;

  Desktop := Server.CreateInstance('com.sun.star.frame.Desktop');

  LoadParams := VarArrayCreate([0, -1], varVariant);

   {Create new document}
  Document := Desktop.LoadComponentFromURL('private:factory/swriter', '_blank', 0, LoadParams);

   {or Open existing} //you must use forward slashes, not backward!
  //Document := Desktop.LoadComponentFromURL('file:///C:/my/path/mydoc.doc', '_blank', 0, LoadParams); 

  TextCursor := Document.Text.CreateTextCursor;

   {Insert existing document}  //Substitute your path and doc
  TextCursor.InsertDocumentFromURL('file:///C:/my/path/mydoc.doc', LoadParams);
end.

More comprehensive examples can found here:

  • OLECreateTextDoc: Create and populate a text document with paragraph, table and frame
  • OLEEditTextDoc: Load an existing text document, search with regular expression, replace text and add rows to a table

Office on Windows

Here’s a simple example of how to open a document with your program using the Word Automation server. Note that this example works only on Windows. This will work with both delphi and fpc.

program TestMsOffice;

{$IFDEF FPC}
 {$MODE Delphi}
{$ELSE}
 {$APPTYPE CONSOLE}
{$ENDIF} 

uses
  SysUtils, Variants, ComObj;

const
  ServerName = 'Word.Application';
var
  Server     : Variant;
  w:widestring;
begin
  if Assigned(InitProc) then
    TProcedure(InitProc);

  try
    Server := CreateOleObject(ServerName);
  except
    WriteLn('Unable to start Word.');
    Exit;
  end;

   {Open existing document}  //Substitute your path and doc
  w:= UTF8Decode('c:mypathmydoc.doc');
  Server.Documents.Open(w); //OLE uses BSTR (http://msdn.microsoft.com/en-us/library/windows/desktop/ms221069(v=vs.85).aspx). Only widestring is compatible with BSTR in FPC, so conversion is needed for nonlatin chars.
  Server.Visible := True;  {Make Word visible}

end.

Here is a sample code how to work in an open Word document, using the Word Automation server.

var
  Server: Variant;
begin
  try
    Server := GetActiveOleObject('Word.Application');
  except
    try
      ShowMessage('Word not already open create a Word Object');
      // If no instance of Word is running, try to Create a new Word Object
      Server := CreateOleObject('Word.Application');
    except
      ShowMessage('Cannot start Word/Word not installed ?');
      Exit;
    end;
  end;
end;

Limitations:
Since End is a reserved word in FPC it shall be used as a parameter after the & sign.

Server.ActiveDocument.Application.Selection.start:=Server.ActiveDocument.Application.Selection.&end+1;

A lot of examples for Excel are available on the German wiki page ExcelAutomation/de.

Using the fpXMLXSDExport unit

FPC 2.6 and newer contain the fpXMLXSDExport unit, part of the FCL-DB export components. With that, you can export datasets to various XML formats, including a Microsoft Access-compatible format and a Microsoft Excel-compatible format.

The Access format can output XML with or without an embedded XSD data/table definition. Note that exporting binary/BLOB type data needs additional action at the Access import end, as Access does not support proper binary fields, only OLE fields.

In the Excel format, multiline text fields are not supported at the moment: the line ends are removed during the export.

Lazarus provides a visual component for this: after installing the lazdbexport package, you will see the TXMLXSDExporter component on the Data Export tab

See fpXMLXSDExport for details.

Using the FPSpreadsheet Library

Another way to automate repetitive work with spreadsheets is to use the FPSpreadsheet library. It can read and write spreadsheets in several formats and it doesn’t require having any external application installed on the machine.

The advantages are that fpspreadsheet is 100% Object Pascal code, and it requires no external libraries or programs.

Writing an Excel file using ADO

please write me.

Reading/Writing an Excel file using OLE

This method needs Excel to be installed on the user’s machine because it uses OLE to access it.

Keep in mind that this method starts Excel in the background, which opens the file and works with it like a real user.

  • Create a new form with button, stringgrid and edit.
  • Create a new Excel file and fill a few cells.

excel123.png

Example — Open/Read Excel file:

uses .....  comobj;

procedure TForm1.Button1Click(Sender: TObject);

Var   XLApp: OLEVariant;
      x,y: byte;
      path: variant;

begin
 XLApp := CreateOleObject('Excel.Application'); // requires comobj in uses
 try
   XLApp.Visible := False;         // Hide Excel
   XLApp.DisplayAlerts := False;
   path := edit1.Text;
   XLApp.Workbooks.Open(Path);     // Open the Workbook
   for x := 1 to 4 do
    begin
     for y := 1 to 6 do
      begin
       SG.Cells[x,y] := XLApp.Cells[y,x].Value;  // fill stringgrid with values
      end;
    end;
 finally
   XLApp.Quit;
   XLAPP := Unassigned;
  end;

If you want to make some changes and you want them to write back into the Excel, file you can use:

XLApp.Cells[x,y].Value := SG.Cells[y,x];

If you want to save:

XLApp.ActiveWorkBook.Save;

Read/Writing an Excel file using the SpreadSheet Interface Component

The component provides a library interface, abstracting the Excel COM and the Calc Open Office UNO interfaces.
The component is available here:
http://tcoq.free.fr/composants.html (Link verified in May 2016)

Since Automation is not yet available, but COM is available, the Excel interface component provides a set of Lazarus classes encapsulating calls to the Excel COM interface (the one below the Automation). It hides most of the drudgery of working with low-level code.
Be careful, this is a work-in-progress. Use it at your own risk.

Functionality:

  • creating and loading excel workbooks,
  • saving workbooks,
  • creating and accessing sheets,
  • getting values and setting values (and formulas) in cells,
  • getting and changing color of cells,
  • getting and changing column height and row width,
  • creating comments,
  • creating shapes,
  • creating charts.

Inits first.

  IMPLEMENTATION
  USES
    ExcelUtilities,
    SpreadSheetInterfaces ;

  VAR
   aCell    : IRange ;
   aValue   : OleVariant ; // Not sure about this, but it works. ie( Edit.Text := STRING(aValue); )
   ExcelApp : TExcelApplication ;
   ExcelWbs : IWorkBooks ;

  ExcelBook   : IWorkBook ;
  ExcelSheet  : ISheet ;
  ExcelSheets : ISheets ;

Getting a sheet is simple:

  // Initializing the common excel workbook:
  ExcelApp         := TExcelApplication.Create(nil) ;
  ExcelApp.Active  := True ;
  ExcelApp.Visible := True ;

  ExcelWbs    := ExcelApp.WorkBooks ;
  ExcelBook   := ExcelWbs.Add ;
  ExcelSheets := ExcelBook.Sheets ;
  ExcelSheet  := ExcelSheets.Sheet(1) ;

Playing around with cells is simple too:

  // adding a value
  aCell := ExcelSheet.Cells(1, 1) ;
  aCell.Value := 10;

  // adding a formula
  aCell := ExcelSheet.Cells(2,1) ;
  aCell.Formula := '=A1+10' ;

  // getting the value computed in Excel
  aValue := aCell.Value ;

The test case provided has many more examples.

Copy HTML to the clipboard

You can copy HTML to the clipboard which is understood by many applications. This way you can copy formatted text. For those applications that only understand text put plain text too.

Microsoft Office applications require HTML to be pasted onto the clipboard in a more complex format than described here. See here for an example that works with Microsoft Office.

uses
  ClipBrd;
...
  // register the mime type for text/html. You can do this once at program start:
  ClipbrdFmtHTML:=RegisterClipboardFormat('text/html');
...
  // Clear any previous formats off the clipboard before starting
  Clipboard.Clear;

  // put text and html on the clipboard. Other applications will choose the best format automatically.
  ThePlainUTF8Text:='Simple text';
  Clipboard.AsText:=ThePlainUTF8Text; 

  AsHTML:='<b>Formatted</b> text'; // text with formattings
  Clipboard.AddFormat(ClipbrdFmtHTML,AsHTML[1],length(AsHTML));

See also

  • Clipboard
  • Powerpoint Automation

External links

  • Excel file format — description on OpenOffice website

Модератор: Модераторы

Excel

Искала, но подходящей темы не нашлось (либо плохо искала :roll: ). Цель вот какая — есть документ blank_z.xls. Он служит как заготовка, как пустая форма. Есть программа, которая соединяется с базой MySQL. Необходимо открыть этот файл .xls и записать в него данные в определенные ячейки из определенных полей с формы. В делфи это сделалось очень просто:

Код: Выделить всё
procedure TPrintForm.BitBtn1Click(Sender: TObject);
var
path: string;
Excel, Sheet: Variant;
begin
path:=ExtractFilePath(Application.ExeName)+'Reports/blank_z.xls';
Excel:=CreateOLEObject('Excel.Application');
Excel.WorkBooks.Open[path];
Excel.Visible:=true;

Excel.Range['B6']:=PrintForm.DBEdit1.Text;
Excel.Range['B7']:=PrintForm.DBEdit2.Text;
Excel.Range['G7']:=PrintForm.DBEdit3.Text;
Excel.Range['I7']:=PrintForm.DBEdit4.Text;
Excel.Range['K7']:=PrintForm.DBEdit5.Text;
Excel.Range['M7']:=PrintForm.DBEdit6.Text;
Excel.Range['C8']:=PrintForm.DBEdit7.Text;
Excel.Range['D9']:=PrintForm.DBEdit8.Text;
Excel.Range['I15']:=PrintForm.DBEdit9.Text;
end;

Первую часть открытия файла скопировала в проект Lazarus. Но ничего не работает. Ругается на переменную path.

Alana
новенький
 
Сообщения: 24
Зарегистрирован: 08.09.2010 16:29:13

Re: Excel

Сообщение xcod » 13.09.2010 11:42:44

А как ругается?
и где

xcod
постоялец
 
Сообщения: 108
Зарегистрирован: 07.08.2009 12:37:23

Re: Excel

Сообщение Alana » 13.09.2010 13:25:05

PrintUnit.pas(39,22) Error: Incompatible types: got «AnsiString» expected «LongInt»
А если в строке

Код: Выделить всё
Excel.WorkBooks.Open[path];

переменную path взять в квадратные скобки, то программа компилируется. Но при попытке запустить файл .xls выдает ошибку:
Изображение
Красиво, правда? :)

Alana
новенький
 
Сообщения: 24
Зарегистрирован: 08.09.2010 16:29:13

Re: Excel

Сообщение Kitayets » 13.09.2010 14:09:29

2Alana

вместо:

Код: Выделить всё
Excel.WorkBooks.Open[path];

нужно:

Код: Выделить всё
Excel.WorkBooks.Open(path);
Kitayets
постоялец
 
Сообщения: 169
Зарегистрирован: 05.05.2010 21:15:24

Re: Excel

Сообщение Alana » 13.09.2010 14:33:12

Kitayets писал(а):нужно:

Код: Выделить всё
Excel.WorkBooks.Open(path);

А если в строке:

Код: Выделить всё
Excel.WorkBooks.Open[path];

переменную path взять в круглые скобки, то программа компилируется. Но при попытке запустить файл .xls выдает ошибку:
Изображение

Alana
новенький
 
Сообщения: 24
Зарегистрирован: 08.09.2010 16:29:13

Re: Excel

Сообщение Kitayets » 13.09.2010 14:49:40

извиняюсь, что не внимательно прочитал.

1. правильный вариант — с круглыми скобками
2. ругается, видимо потому, что не нравится кодировка строки (UTF-8).

попробуйте:

Код: Выделить всё
1. Excel.WorkBooks.Open(UTF8Decode(path));
Kitayets
постоялец
 
Сообщения: 169
Зарегистрирован: 05.05.2010 21:15:24

Re: Excel

Сообщение GrayEddy » 13.09.2010 15:06:48

Кхе, опять грабли. Ну не поддерживает Lazarus (FreePascal) OLE (пока).

GrayEddy
постоялец
 
Сообщения: 375
Зарегистрирован: 06.05.2005 09:37:56

Re: Excel

Сообщение m_guest » 13.09.2010 15:17:49

Можно попробовать использовать сторонние компоненты вроде fpspreadsheet

m_guest
постоялец
 
Сообщения: 193
Зарегистрирован: 14.08.2005 15:10:21

Re: Excel

Сообщение Alana » 13.09.2010 15:59:11

GrayEddy писал(а):Кхе, опять грабли. Ну не поддерживает Lazarus (FreePascal) OLE (пока).

Ну вот, как печально :( А мне очень excel нужен….

Alana
новенький
 
Сообщения: 24
Зарегистрирован: 08.09.2010 16:29:13

Re: Excel

Сообщение WindOfPain » 13.09.2010 16:08:39

Как вариант, сделать dll библиотеку для работы с Excel в Turbo Delphi, и уже через нее из Lasarus ковыряться в Excel.

Аватара пользователя
WindOfPain
новенький
 
Сообщения: 33
Зарегистрирован: 01.09.2009 21:18:23
Откуда: Санкт-Петербург

Re: Excel

Сообщение Vadim » 13.09.2010 16:13:28

Alana писал(а):А мне очень excel нужен….

Записывайте свои данные в XML-файл. Он Экселем прекрасно открывается и даже UTF-8 его не смущает. ;)
Чтобы узнать, каким образом записывать данные, надо создать образец в Экселе с небольшим кол-вом аналогичных данных и необходимым оформлением. Потом сохранить как XML и посмотреть в любом текстовом редакторе, который поддерживает UTF-8, что и в каком порядке туда записалось. После чего можно просто записывать в текстовый файл с помощью WriteWriteLn, либо TStrringList.Add(…) и TStringList.SaveToFile(Имя_файла).

Vadim
долгожитель
 
Сообщения: 4112
Зарегистрирован: 05.10.2006 08:52:59
Откуда: Красноярск

Re: Excel

Сообщение coyot.rush » 13.09.2010 16:27:54

читаем тут CSV http://ru.wikipedia.org/wiki/CSV
и тут Импорт и экспорт текстовых файлов http://office.microsoft.com/ru-ru/excel-help/HP010099725.aspx

Добавлено спустя 7 минут 9 секунд:

Vadim
Записывайте свои данные в XML-файл. Он Экселем прекрасно открывается и даже UTF-8 его не смущает. ;)
Чтобы узнать, каким образом записывать данные, надо создать образец в Экселе с небольшим кол-вом аналогичных данных и необходимым оформлением. Потом сохранить как XML и посмотреть в любом текстовом редакторе, который поддерживает UTF-8, что и в каком порядке туда записалось. После чего можно просто записывать в текстовый файл с помощью WriteWriteLn, либо TStrringList.Add(…) и TStringList.SaveToFile(Имя_файла).

Reverse Engineering очень увлекательное занятие :roll:
Команда из OpenOffice постоянно реферсит форматы MSO и все время находиться какие то проблемы при открытии :!:

Аватара пользователя
coyot.rush
постоялец
 
Сообщения: 306
Зарегистрирован: 14.08.2009 08:59:48

Re: Excel

Сообщение Vadim » 13.09.2010 17:02:33

coyot.rush писал(а):Команда из OpenOffice постоянно реферсит форматы MSO и все время находиться какие то проблемы при открытии

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

Vadim
долгожитель
 
Сообщения: 4112
Зарегистрирован: 05.10.2006 08:52:59
Откуда: Красноярск

Re: Excel

Сообщение Odyssey » 13.09.2010 17:26:08

CSV тут может не хватить. Самый простой и быстрый для реализации способ предложил Vadim. Я бы предложил дополнить его не генерацией, а банальной заменой по подстановочным символам. По шагам:
* Делаем резервную копию файла XLS и открываем его.
* В ячейку B6 вставляем текст, например «{DBEdit1}» (главное чтобы такого текста больше ни в какой ячейке не было)
* В B7 вставляем {DBEdit2}
* В G7 вставляем {DBEdit3}
* и т.д.
* сохраняем файл как XML (что-то типа Excel 2003 XML)

Потом из программы делаем что-то вроде:

Код: Выделить всё
var
  Path: string;
  ReportPath: string;
  ExcelData: TStringList;
  Buffer: string;
begin
  Path:=Utf8Decode(ExtractFilePath(Application.ExeName)+'Reports/blank_z.xml');
  ReportPath:=Utf8Decode(ExtractFilePath(Application.ExeName)+'Reports/temp_report.xml');
  ExcelData := TStringList.Create;
  ExcelData.LoadFromFile(path);
  Buffer := ExcelData.Text;
  Buffer := StringReplace(Buffer, '{DBEdit1}', PrintForm.DBEdit1.Text, []);
  Buffer := StringReplace(Buffer, '{DBEdit2}', PrintForm.DBEdit2.Text, []);
  Buffer := StringReplace(Buffer, '{DBEdit3}', PrintForm.DBEdit3.Text, []);
  // и т.д.
  ExcelData.Text := Buffer;
  ExcelData.SaveToFile(ReportPath);
  FreeAndNil(ExcelData);
  // открываем созданный файл в Excel
  ExecuteProcess('путь к excel', ReportPath);
end;

Код разумеется не тестировал и не оптимизировал, думаю идея понятна. В пути к excel можно попробовать указать просто excel.exe (или как он там называется, возможно он уже в path, вроде бы у меня такое было). Если не получится — можно устанавливать в путь по умолчанию (C:Program Files…) и разрешать менять в настройках программы.

Odyssey
энтузиаст
 
Сообщения: 580
Зарегистрирован: 29.11.2007 17:32:24

Re: Excel

Сообщение evd » 13.09.2010 19:01:11

У меня вот такой код работает. FPC 2.4.0, Lazarus 0.9.29

Код: Выделить всё
procedure TForm1.Button1Click(Sender: TObject);
var
path: string;
Excel, Sheet: OleVariant;
begin
  path:=ExtractFilePath(Application.ExeName)+'Reportsblank_z.xls';
  Excel:=CreateOLEObject('Excel.Application');
  try
    Excel.WorkBooks.Open(WideString(UTF8Decode(path)));
    Excel.Visible:=true;
    Excel.Range('B6'):='B6';
    Excel.Range('B7'):='B7';
    Excel.Range('G7'):='G7';
    Excel.Range('I7'):='I7';
  except
    on E:EOleException do
      ShowMessage(UTF8Encode(E.Message));
  end;
end;
Аватара пользователя
evd
новенький
 
Сообщения: 21
Зарегистрирован: 13.09.2009 09:42:28
Откуда: Вологда
  • Профиль
  • Сайт


Вернуться в Lazarus

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 11

Категории раздела
Религия
[2]

Буддизм, Христианство, Агни Йога, Йога Васиштха и др. Йоги, Индуизм, Искусство Жизни, Шри Шри Рави Шанкар, Конфуций, Хагакуре Сокрытое в листве, Ицхак Одизес, Наталья Грейс, Ошо, Тантра, Даосизм

Программы
[5]

Описание различных программ

Программирование
[24]

Исходники, примеры, ссылки, программы C++, Delphi, Python, Html, Java но в основном Delphi, Python, Html, создание игр, Blender Game Engine

Blender
[16]

Бесплатный редактор трехмерного моделирования

CADCAMCAE
[0]

Solid Works, Nastran, Patran, Ansys и др.

Krita
[4]

Материалы по свободному графическому редактору

Интернет
[0]

Интересная информация о работе с интернетом

IrfanView
[1]

Возможности программы

Игры
[2]

Железо
[1]

Различная электроника

Статистика

Онлайн всего: 1

Гостей: 1

Пользователей: 0

Главная » 2016 » Сентябрь » 14 » Работа с Excel через Lazarus


17:07

Работа с Excel через Lazarus

1. Чтение готового файла Excel и запись в него через компонент Lazarus — FPSpreadsheet описано здесь

Работа с Excel

2. Создание нового файла Excel и запись в него через компонент Lazarus — FPSpreadsheet описано ниже (взято с http://wiki.lazarus.freepascal.org/FPSpreadsheet)

{
excel5demo.dpr
 
Demonstrates how to write an Excel 5.x file using the fpspreadsheet library
 
You can change the output format by changing the OUTPUT_FORMAT constant
 
AUTHORS: Felipe Monteiro de Carvalho
}
program excel5demo;
 
{$mode delphi}{$H+}
 
uses
 Classes, SysUtils, fpstypes, fpspreadsheet, fpsallformats, laz_fpspreadsheet;
 
const 
 OUTPUT_FORMAT = sfExcel5;
 
var
 MyWorkbook: TsWorkbook;
 MyWorksheet: TsWorksheet;
 MyFormula: TsRPNFormula;
 MyDir: string;
begin
 // Initialization
 MyDir := ExtractFilePath(ParamStr(0));
 
 // Create the spreadsheet
 MyWorkbook := TsWorkbook.Create;
 try
 MyWorksheet := MyWorkbook.AddWorksheet('My Worksheet');
 
 // Write some number cells
 MyWorksheet.WriteNumber(0, 0, 1.0);
 MyWorksheet.WriteNumber(0, 1, 2.0);
 MyWorksheet.WriteNumber(0, 2, 3.0);
 MyWorksheet.WriteNumber(0, 3, 4.0);
 
 // Write the formula E1 = A1 + B1
 MyWorksheet.WriteFormula(0, 4, 'A1+B1');
 
 // Creates a new worksheet
 MyWorksheet := MyWorkbook.AddWorksheet('My Worksheet 2');
 
 // Write some string cells
 MyWorksheet.WriteText(0, 0, 'First');
 MyWorksheet.WriteText(0, 1, 'Second');
 MyWorksheet.WriteText(0, 2, 'Third');
 MyWorksheet.WriteText(0, 3, 'Fourth');
 
 // Save the spreadsheet to a file
 MyWorkbook.WriteToFile(MyDir + 'test' + STR_EXCEL_EXTENSION, OUTPUT_FORMAT);
 finally
 MyWorkbook.Free;
 end;
end.

P.S.

свой вариант 2 я создал как комбинацию 1-го (90%) и 2-го варианта 

вместо

MyWorkbook.ReadFromFile(‘Путь к файлу.xls’, sfExcel8);

я использовал

MyWorkbook := TsWorkbook.Create;

  • 1
  • 2
  • 3
  • 4
  • 5

Категория: Программирование |
Просмотров: 6271 |

| Рейтинг: 0.0/0

Архив записей
  • 2014 Сентябрь
  • 2014 Октябрь
  • 2016 Сентябрь
  • 2017 Апрель
  • 2017 Август
  • 2020 Январь
  • 2020 Февраль
  • 2020 Май
  • 2020 Июнь
  • 2021 Апрель
  • 2021 Июнь
  • 2021 Июль
  • 2021 Сентябрь
  • 2021 Декабрь
  • 2022 Январь
  • 2022 Февраль
  • 2022 Апрель
  • 2022 Май
  • 2022 Июнь
  • 2022 Июль
  • 2023 Февраль

OExport allows you to generate and read XLSX, XLS, ODS and CSV spreadsheets directly from Delphi & Lazarus.
It has also an import feature — you can extract data from XLSX, XLS, ODS and CSV files.
Please see the feature matrix below for more details.

  • Features
  • Screenshots
  • License
  • Order
  • Downloads
  • Change log

Features

Library design

  • Native pascal object oriented code
  • No external dll libraries are required
  • No dependency on Excel or Calc installation (no OLE)
  • Full unicode support even for non-unicode Delphi versions (D7, D2007 etc.)
  • Write-On-The-Fly and Read-On-The-Fly: export and import huge tables without the need to store the whole document in memory.
  • Reasonably fast (see performance table below).

Officially supported platforms

  • Delphi 5, 6, 7, 2005, 2006, 2007: VCL + full unicode support thanks to WideString.
  • Delphi 2009, 2010, XE: VCL
  • Delphi XE2, XE3, XE4, XE5, XE6, XE7, XE8, 10 Seattle, 10.1 Berlin: VCL + FireMonkey, 32bit + 64bit Windows, Mac OSX.
    Important notice: Delphi ARM compiler (iOS) was not tested yet and may be unsupported.
  • Lazarus 1.0.8: 32bit + 64bit Windows, Linux and Mac OSX (XLS: Little Endian platforms only)

Template Engine

  • Currently only loading of XLSX/XLTX and XLS/XLT templates is supported.
  • Automatically replace cell values and modify cells.
  • Automatically add and process rows as they are defined in the template.
  • Save the generated template in all formats OExport supports: XLSX/ODS/XLS/CSV!

Feature Overview

See the following files for a fast feature overview. These files have been directly exported with OExport:

  • XLSX: oexport-fulldemo.xlsx
  • ODS: oexport-fulldemo.ods
  • XLS: oexport-fulldemo.xls

You can generate those files with the demo application you find in the FREE package (see download tab).
They have not been edited after the export in any way.
Please note that XLS exporter doesn’t support images and charts and therefore you won’t see them in the exported XLS file.
The full source code that was used to generate them
can be obtained from the documentation.

Feature Matrix

yes = Supported; yes = Partially supported; no = Not supported; n/a = Not available
Feature Export Import
XLSX ODS XLS CSV XLSX ODS XLS CSV
Cell types: string, number, percent, currency, scientific, fraction, time, date, datetime yes yes yes yes yes yes yes yes
Rich text in cells yes yes yes n/a yes yes yes n/a
Custom number format yes yes yes n/a yes no yes n/a
Hyperlinks for string cells yes yes yes n/a yes no yes n/a
Formulas for all cell types yes yes yes yes yes yes yes n/a
Cell, row, column and worksheet formatting: horizontal + vertical alignment, wrap text, font, background color, borders (color, size and style), text orientation and rotation yes yes yes n/a yes no yes n/a
Column widths + row heights yes yes yes n/a yes no yes n/a
Column + row grouping yes yes yes n/a yes no yes n/a
Conditional formatting yes yes yes n/a yes no yes n/a
Data validation yes yes yes n/a yes no yes n/a
Column + row span (merged cells) yes yes yes n/a yes no yes n/a
Print settings: page header & footer, page orientation, page margins, page order, page breaks, print scale, table centering, repeat columns & rows, grid lines, table headers yes yes yes n/a yes no yes n/a
Fixed cells (window fixed scrolling) yes yes yes n/a yes no yes n/a
Named cells yes yes yes n/a yes no yes n/a
Cell & worksheet protection: with and without password yes yes yes n/a yes no yes n/a
Autofilter yes yes no n/a yes no no n/a
Comments yes yes no n/a yes no no n/a
Images: JPEG, PNG, GIF, TIFF
 + fill, border, shadow
yes yes no n/a yes no no n/a
Charts: bars, columns, lines, areas, bubble, scatter; different line, fill, marker and axes styles, sizes, colors; titles … yes yes no n/a no no no n/a

Row and column limits

OExport is able to read and write the maximum permitted row and column counts of every supported format.
The limits are the following:

Row count Column count
XLSX 1’048’576 16’384
ODS 1’048’576 1’024
XLS 65’536 256
CSV 2’147’483’647 2’147’483’647

Performance

The performance of OExport may vary on used compiler. The best figures are reached
with Delphi 2009 and newer.
The following times were measured on an old laptop from 2007
(Intel Core 2 Duo, 1.8 GHz, 4.0 GB RAM, Win 7 32bit).
Files consisted of 1 million string cells
with shared strings table (SST) either off or on.

1 million string cells Export Import
XLSX ODS XLS CSV XLSX ODS XLS CSV
D2009+ SST off 35 s 32 s 22 s 15 s 70 s 84 s 8 s 15 s
SST on 44 s 32 s 27 s 15 s 105 s 84 s 9 s 15 s
D5-D2007 SST off 92 s 75 s 44 s 42 s 178 s 170 s 17 s 32 s
SST on 100 s 75 s 50 s 42 s 260 s 170 s 20 s 32 s
Lazarus SST off 50 s 48 s 37 s 29 s 94 s 103 s 8 s 26 s
SST on 55 s 48 s 40 s 29 s 124 s 103 s 8 s 26 s

OFiller

  • OFiller: fill DOCX (Word 2007-2013), ODT (OpenOffice Writer), XLSX (Excel 2007-2013), XLS (Excel 97-XP), ODS (OpenOffice Calc) templates

License

OEXPORT LICENSE INFORMATION
===========================


Copyright (C) 2011-2017 Ondrej Pokorny
  http://www.kluug.net

This license is applicable to all files distributed in this archive if not
stated differently.
The commercial part of the license text (FULL version) applies to orders
after March 14th, 2017.


*** BEGIN LICENSE BLOCK *****

OExport 2.x LICENSE
-------------------

 1) You may use OExport if:
     a. You use the FREE version.

        OR

     b. You have a commercial license for the FULL version.

 2) Limitations of the FREE version
     a. There are no limitations per workplace. You can use OExport FREE
        both for commercial and non-commercial purposes.

     b. Only the first worksheet will be exported or imported and a maximum
        of 40 rows and 10 columns.

     c. You may not modify, decompile, disassemble, reverse engineer or
        translate OExport FREE.

 3) Limitations of the FULL version
     a. Only developers who work for the license holder company may use OExport.
        That includes freelancers but only in projects assigned to them by the license
        holder company.

     b. The number of active developers who use OExport may not exceed the total number
        of licensed developers that the license(s) of the holder company provide(s) for.

 4) Transfer of FULL version licenses

     a. Licenses may be transferred to new developers who work for the
        license holder company if all other requirements are met (especially point 3b).

     b. The license may be transferred only as a whole to a different company.
        Example: you buy a 3-developer license. You may transfer it completely to
        a different company. You may not split the license and transfer 1-developer
        license to a different company and keep 2-developer license.

 4) License validity

     a. The license is perpetual.

     b. You get 2 years of free updates and new releases, starting from the day
        of purchase. After this period you can order extra 2 years of updates
        (starting from the day of update expiration) for 60% of the license price
        at the moment of update expiration.

 5) You may NOT use OExport for:
     a. Writing libraries and applications that are in direct or indirect
        competition with OExport or tools whose main purpose is providing OExport
        functionality. An example would be to build a public XLSX- ODS- or
        XLS-Export library or a conversion tool etc. OExport functionality
        has to be an extension to an existing application (e.g. export in
        an accounting software).
        If you need a special license, please contact the author.

 6) Redistribution of the source code and the DCU's
     a. OExport source code and DCU's may not be redistributed on any kind
        of media or offered for download on any internet server without
        the author's explicit permission.

 7) Redistribution in binary form
     a. If you do not have a FULL commercial license, you have to attribute
        OExport in e.g. the About Dialog of your software.
        The attribution must contain the name ("OExport") and my homepage
        ("http://www.kluug.net").

     b. If you do have a license for the FULL version, no attribution is required.

 8) Additional software licensed with OExport
     a. If you purchase OExport, you also get a special OXml commercial license.
        This license allows you to use OXml only as part of OExport (because
        OExport uses OXml for handling XLSX and ODS files).
        You are not allowed to use OXml separately - in this case you have
        to obtain OXml commercial license as well.
        This paragraph applies to OXml which is located in OXml directory.

 9) Limited Warranty
     a. THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
        EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
        WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
        THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS
        WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF
        ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT SHALL
        KLUUG.NET OR ANY OTHER PARTY WHO MAY HAVE DISTRIBUTED THE SOFTWARE AS
        PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
        SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
        INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA
        OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
        PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER
        PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGES.


***** END LICENSE BLOCK *****

Commercial license

All commercial licenses include full source code of OExport that can be used
on all officially supported platforms.

You may order a roality-free commercial license for a specified number of developers using OExport in your company.
A commercial license allows you to use OExport in any kind of application commercial or freeware that does not break the Section 4. of the license («DLL library»).

You also get 2 years free updates and new releases with priority email support.
With these resources you can add XLSX/ODS support to your applications quickly and with ease.

Go to OExport online help.

Pricing & Order

Online orders are managed by PayPal. I also accept bank transfers to my bank account.
In this case, please send me an email with your billing address and I send you my account number.

You receive an invoice per email after your payment.

All prices are without VAT.

I offer you a 30-days money-back guarantee if you can’t use OExport for
what is advertised on this page (because of bugs, compatibility problems etc.).

Commercial licenses & help access

OExport
for 1 developer
+ 2 years of updates
EUR 210,- (~ USD 210,-)
OExport
for max. 3 developers within one company
+ 2 years of updates
EUR 420,- (~ USD 420,-)
OExport
for max. 5 developers within one company
+ 2 years of updates
EUR 630,- (~ USD 630,-)
OExport
for unlimited developers within one company
+ 2 years of updates
EUR 840,- (~ USD 840,-)

Change log

OEXPORT RELEASE INFORMATION
===========================

  Version 2.37 (2023-01-01)
    Bug fixes
      - Recalculation engine: fix equal and not-equal operator for strings and booleans
      - make compatible with latest OXml
      - XLS: fix error when last string was interrupted by a record break
      - fix default column properties for XLSX


  Version 2.36 (2022-03-25)
    Bug fixes
      - ExcelCellWidthToPx to interface
      - Remove OWideSupp_Vcl.pas
      - Fix loading XLSX without theme file


  Version 2.35 (2021-09-30)
    New features
      - Delphi 11 support


  Version 2.34 (2021-06-09)
    Bug fixes
      - fix TExportRange.ImportAsXLSX for column and row ranges
      - TExportCell.DoCalculateColWidth: optimization for empty text
      - Recalculate formulas: fix SUBTOTAL
      - force saving XLS RPN formulas even if they haven't been created internally
      - new property RecalculateFormulasOnExport
      - RecalculateFormulas - allow non-numeric cells for range and function recalculation (e.g. the concatenate function works on string RecalculateFormulas - fix setting of result value for various cell types
      - OOLEStorage: EOOleStorageException in case of an empty file
      - (breaking change) change RecalculateFormulas parameters to set and recalculate formulas before exporting just once
      - Fix TOExportTemplate.StartProcessingRows


  Version 2.33 (2021-02-02)
    New features
      - OExportTemplate: allow to work with specific sheets only
      - Functions: add SUBTOTAL

    Bug fixes
      - Read XLSX: fix palette
      - OFiller: merge also text nodes without rPr node if they have texts
      - OFiller: replace loses international characters
      - TExportCell.Transform: try to convert values
      - OExport: fix Excel 1900 is leap year
      - GetTextExtent - try various DPI settings because of Excel comment boxes
      - OExport: NormSheetName as class function
      - Sheet: fix forbidden characters in sheet name


  Version 2.32 (2020-07-24)
    New features
      - Delphi 10.4 packages

    Bug fixes
      - OExport fix invalid '>'
      - TExportCellComment.DoCalculateSize: more width


  Version 2.31 (2020-05-12)
    Bug fixes
      - various bug fixes


  Version 2.30 (2019-07-27)
    New features
      - Delphi 10.3.2 support (with MacOS 64bit support)
      - OFiller: TOFillerXLSX.ReplaceCellAtAddress

    Bug fixes
      - Fix multithreading support
      - OExportRTF: fix last char & line feed offsets in StringCellToRichEdit
      - XLSReadString: always read flags (bug was when empty formula string token was read)
      - TOExport.RecalculateFormulas: use only GuessCellType for guessing and not for final cell type because it doesn't have to be correct
      - Fix formulas with named ranges in data validation


  Version 2.29 (2018-12-31)
    New features
      - Delphi 10.3 support
      - OFiller: add TReplaceImageSizeRatio.srImageSetSmaller
      - OFiller: add aAlign, aVAlign to ReplaceImage (supported in XLSX only)

    Bug fixes
      - OExport drawings: use position and size in Double precision
      - fix reading Excel 2016 documents
      - fix CalculateColWidthsRowHeights for hidden columns&rows
      - fix importing XLSX named cell col+row ranges


  Version 2.28 (2018-10-25)

    New features
      - Basic HTML Export (first simple version).

    Bug fixes
      - Update package names so that they do not collide with unit names
      - HTML exporter: fix column widths and row heights
      - OFiller: support header&footer in DOCX
      - OExport: fix column width on high-dpi systems
      - OFileUtils: fix GetUniqueFileName
      - HTML Export improvements
      - OFiller: TOFillerXLSX.ReplaceHyperlink
      - OFiller: TOFillerXLSX.DeleteImage
      - OFiller: fix image size
      - Fix selection if split is used.
      - Export cell: fix assign drawings
      - Formula recalculation engine: support IS* functions (IsBlank, IsErr, IsError, IsLogical, IsNA, IsNonText, IsNumber, IsRef, IsText)
      - Formula engine: support Count and CountA
      - OExport: support meta information (XLSX, ODS)
      - NoGUI: move LCLProc to interface uses
      - Add TExportWorkSheet.DeleteEmptyRows
      - RPNFormula: support VLookup
      - RPNFormula: fix IsSingleOperatorAfterThisOperator
      - XLSX: fix loading boolean cells without assigned value
      - Fix RNP Column/Row types
      - Update dir ignore properties
      - Rename IntegerList to OIntegerList to avoid name collisions
      - VCL: Fix ExecuteSaveDialog not returning filename
      - OZip: add IsValid stream overload
      - OFiller: better exception for invalid file format
      - XLS formula import: check valid worksheet index
      - XLS palette: don't use default and system colors because Excel cannot open cell property dialog if they are used.
      - Add AutoFilter button width to calculated column width
      - Handle Excel limit of 1024 page breaks.
      - TExportCell.AssignTo: add CalculateColWidth
      - Add EXCEL_REC_CODEPAGE and EXCEL_REC_WINDOWPROTECT
      - OExport: fix formula call stack
      - Add TOExporterText.DeleteEmptyCellsFromEnd
      - XLS export: fix record order. Fix target pane index in EXCEL_REC_PANE
      - TOExporterText: new WriteBOM property


  Version 2.27 (2017-04-10)

    New features
      - OFiller: support named cells.
      - initialize OExportDateFormat and OExportTimeFormat directly in OExport
      - formula recalculation: add support for MID, LEN, IF, FIND functions
      - add XLS support for SUMIF(), COUNTIF() (no recalculation yet).

    Bug fixes
      - fix mouse wheel not working in Excel 2000
      - fix too wide columns for calculated cells
      - XLS: fix writing long strings to SST
      - PaperType support
      - OExport_Vcl: fix multithreading
      - Fix Delphi 7 performance bottleneck when loading XLSX with a lot of different strings.
      - add ANSI encoding support, CSV: ForceEscapeChar
      - add support for Text() function.
      - Fix Exyz (E1, E2 ...) evaluation
      - CSV exporter: use EscapeChar only if the text must be escaped.
      - fix reading negative RK value.
      - TOExport: add enumerators to WorkSheets, Rows, Cells.
      - fix Id collision when comments and images are used in one sheet.
      - don't move cells in string constants
      - TExportHeaders: add Items[] property
      - TExportCellRange: fix SetBorder=crbAll
      - fix truncation of date only and time only values.
      - OFiller: XLSX: remove formula values in ReplaceCellsEnd - they might be invalid.
      - OFiller: fix XLSX ReplaceCell SharedStrings handling.
      - OFiller: support replacing float values in XLSX via ReplaceCell.
      - OFiller: fix removing tabulators.

    Installation
      * If you want to update OExport, you have to update OXml as well (OXml is included in the zip package too).
        If you use packages, you have to recompile them! (Both OXml and OExport packages).



  Version 2.26 (2016-04-27)

    New features
      - support of prefixed XLSX documents (typically from Mac OSX).
      - added support for comment images.
      - added OExportXLSXCustom (support of custom files in an XLSX container).
      - implement secondary y-axis support for XLSX
      - implement TOExporterText.DecimalSeparator
      - hyperlinks: cell hyperlinks, tooltip support
      - OFiller: support duplicating rows
      - OFiller: intelligent token merge for DOCX
      - OFiller: add TOMergerDOCX
      - Delphi 10.1 Berlin support

    Bugfixes
      - fix hyperlink bug
      - fix a speed problem of on-the-fly export and keep memory consumption low if hyperlinks are used
      - added Polish translation (from Michal Glebowski).
      - fix relative formula evaluation if reference cell doesn't exist.
      - fix formula for TExportCellEmpty
      - fix problem with replacing n to m in formatting strings.
      - use TOHashedStrings in TExporterXLSX_HyperLinks
      - fix AV in TExportNamedCells.Remove

    Installation
      * If you want to update OExport, you have to update OXml as well (OXml is included in the zip package too).
        If you use packages, you have to recompile them! (Both OXml and OExport packages).



  Version 2.25 (2015-12-07)

    Bugfixes
      - renamed ZLib* units to OZLib* units to solve issues with duplicate names
      - fixed conditional formatting and data validation assignment in templates
      - added TExportCols InsertColWithCells, DeleteColWithCells, AssignColWithCells
      - Writeable TExportImage.Ext; make RecalculateFormulas public
      - Added MODE Delphi switches for FPC

    Installation
      * If you want to update OExport, you have to update OXml as well (OXml is included in the zip package too).
        If you use packages, you have to recompile them! (Both OXml and OExport packages).



  Version 2.24 (2015-09-16)

    New features
      + Delphi 10 Seattle support.

    Bugfixes
      * prevent AV during import of XLSX comments.
      * fixed TExportRow.AddCellVariant
      * added ApplicationVersion and set default values for Application/ApplicationVersion to meet Excel 2007 due to LibreOffice compatibility.
      * check for circular references in formula recalculation
      * fixed ROW() and COLUMN() functions



  Version 2.23 (2015-08-26)

    New features
      + New property TExportWindowSettings.View.
      + New property TOExport.AutoAdjustFormulas - adjust formulas when inserting/deleting rows/cells (the same that Excel does).
          False by default.
      + New properties TExportChartAxis.MaxValue and .MinValue.
      + OFiller procedure ReplaceImage changed to function - it returns number of replaced images.
      + Added new translations. Now OExport supports the following languages:
          English, Czech, German, Danish, French, Hungarian, Dutch, Russian
      + Multiple chart support (TExportChart.SubCharts).
      + Support for enhanced TExportConditionalFormatting and TExportDataValidation ranges - row, col and custom ranges.
        + New property TExportWorkSheet.ConditionalFormattingList.
        + New property TExportWorkSheet.DataValidationList.
        * You can use the lists above for adding CondForm or DataVal for custom ranges.
      + Added TOExportTemplate.FindStringCellsByStrPos. With it you can find a cell that contains a substring.
    Bugfixes
      * Images in cells with colspan were not exported.
      * Fixed bug in DOCX ReplaceImage.
      * XLS relative formula bug fix.
      * Recalculate formulas when loading XLS and cell type doesn't match formula result.
      * OFloatToFraction bug fix.
      * ODS cells with colspan bug fix.
      * TOOleStorage.ReadDirectoryEntry bug workaround.
      - Removed TOFileStream from OFileUtils.pas. TOFileStream is declared in OWideSupp.pas in OXml.

    Installation
      * If you want to update OExport, you have to update OXml as well (OXml is included in the zip package too).
        If you use packages, you have to recompile them! (Both OXml and OExport packages).



  Version 2.22 (2015-04-28)

    New features
      + TCellHAlignment - new options cahCenterContinuous, cahDistributed.
      + XLS formulas support references accross worksheets.
      + TExportChartData.ShowLabels changed from Boolean to TExportChartDataShowLabels.
        ! Use [] for false.
        ! Use [eslValue] for true.
      + TExportChartAxis has new properties: ExcelNumberFormat, OriginAt, OriginValue
      + TExportWorkSheet has new properties: Visibility and NewCellStringFormat
      + TExportWindowSettings has new properties: ShowFormulas and ShowZeros
      + Added data validation support: TExportCell.DataValidation
      + Added support of named cells within a sheet: TExportWorkSheet.NamedCells
      * Improved formula recalculation engine and XLS formula support.
      * Bug fix: zero date/time was exported as empty cell.
      * Removed TPAbbrevia dependency. OExport now uses native ZLib on all platforms. As a result,
        export in Lazarus, Delphi XE and older is faster and uses less memory.
      * Improved image export: images are not loaded into memory if they are
        exported from files.
      * Some other small improvements and bug fixes.


(Please see the installation package for a complete change log).

Понравилась статья? Поделить с друзьями:
  • Lazarus word to string
  • Latin word for out
  • Layout for word document
  • Latin word for origin
  • Layer text boxes in word