Драйвер excel для delphi

Read, Write excel 2002/2003 XML (SpreadsheetML / XML Spreadsheet) library.

// Creating new workbook
var workBook: TZWorkBook;
...
workBook := TZWorkBook.Create();
try
  workBook.Sheets.Add('My sheet');
  workBook.Sheets[0].ColCount := 10;
  workBook.Sheets[0].RowCount := 10;
  workBook.Sheets[0].CellRef['A', 0].AsString := 'Hello';
  workBook.Sheets[0].RangeRef['A', 0, 'B', 2].Merge();
  workBook.SaveToFile('file.xlsx');
finally
  workBook.Free();
end
// Editing exists workbook
var workBook: TZWorkBook;
...
workBook := TZWorkBook.Create();
try
  workBook.LoadFromFile('file.xlsx');
  workBook.Sheets[0].CellRef['A', 0].AsString := 'Hello';
  workBook.Sheets[0].CellRef['A', 0].FontStyle := [fsBold];
  workBook.SaveToFile('file.xlsx');
finally
  workBook.Free();
end

Содержание

  1. OExport — XLSX/XLS/ODS/CSV native Delphi/Lazarus import/export library
  2. Latest Version
  3. Basic info
  4. Why is OExport the best solution for you:
  5. Features
  6. Library design
  7. Officially supported platforms
  8. Template Engine
  9. Feature Overview
  10. Feature Matrix
  11. Row and column limits
  12. Performance
  13. OFiller
  14. Screenshots
  15. Features of OExport
  16. OExport on different operating systems
  17. OFiller
  18. License
  19. Commercial license
  20. Pricing & Order

OExport — XLSX/XLS/ODS/CSV native Delphi/Lazarus import/export library

Latest Version

Basic info

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.

Why is OExport the best solution for you:

  • You can create and read XLSX, XLS, ODS and CSV documents with just one code.
  • A wide range of compilers and platforms is supported:
    Delphi 5, 6, 7, 2005, 2006, 2007, 2009, 2010, XE, XE2, XE3, XE4, XE5, XE6, XE7, XE8, 10 Seattle, 10.1, 10.2, 10.3: Win32, Win64, Mac OSX (not iOS, Android); VCL and FireMonkey
    Delphi 10.3.2, 10.3.3, 10.4, 11: Mac OSX 64bit, Linux 64bit; FireMonkey and console applications (OExport_NoGUI.pas)
    Lazarus: Win32, Win64, Mac OSX, Linux (Little-Endian platforms only); LCL
  • File types are detected automatically.
  • Easy localization to your language. Languages included: English, Czech, German, Danish, French, Hungarian, Dutch, Russian
  • Formula recalculation engine, see http://www.kluug.at/oexport-help/formula-recalculation-engine/ for details.
  • Template engine: automatically process user-defined XLSX/XLS templates.

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:

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

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

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

Screenshots

Features of OExport

OExport on different operating systems

OFiller

License

Commercial license

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.

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.).

Источник

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).

Chat Now

VCL Spreadsheet Control

Read/Write XLSx, XLS, CSV and TXT Files. The DevExpress Spreadsheet provides the UI experience your end users have come to expect from today’s most popular office productivity suite.

Documents & Worksheets

Worksheet Protection

Use password encryption to prevent unauthorized access.

Worksheet Protection

The DevExpress VCL Spreadsheet control enables you to use password encryption to prevent unauthorized users from opening or modifying your workbooks. You can also restrict changes to workbooks, worksheets, and specific ranges. In a protected workbook, users are not allowed to add, delete or rename worksheets.

Various sheets can have different protection levels. For instance, a range in a protected worksheet can be unlocked for specific users while other users may be prompted for a password when they try to edit the range.


Comments

Excel-Inspired Comments

Comments

Comments

You can now annotate worksheets by using comments. End-users can add new comments, edit, hide or delete existing comments, move and resize the comment box.


Cell Formatting & Styles

Create professional-looking worksheets that display your data effectively.

Cell Formatting & Styles

Cell Formatting & Styles

The DevExpress Spreadsheet provides several fast and simple ways to create professional-looking worksheets that display your data effectively. You can use cell styles to apply predefined formats, and other manual formatting features to highlight important data.


Master-Detail

Display master-detail relationships of any complexity.

Master-Detail

Master-Detail

The DevExpress VCL Spreadsheet control allows you to create master-detail reports without writing code.


Printing, Export & Import

The easiest way to printing the contents of your workbook.

Printing, Export & Import

Printing, Export & Import

Turn the contents of your workbook into a printed report with a simple method call or using the Print Dialog. You can customize and preview print output using the Print Setup dialog.

The DevExpress Spreadsheet control supports the following file formats to import and export data:

  • XLS, XLSX;
  • CSV;
  • TXT;
  • XML (export only);
  • PDF (export only);
  • HTML (export only).


Requires the DevExpress Printing System.



«Of all of the tools that I purchase and maintain, the DevExpress tools are the most valuable. The price is reasonable, the tools are fabulous and your support, in the rare case that it is needed, is stellar.»
IntelliMedSoft

Data Analysis

Outlines

Arrange related columns or rows into groups and display summaries for each group.

Outlines

Outlines

Outlining data makes your data easier to view. When you outline Spreadsheet data, you group worksheet data into different levels based on column and row headings. You can quickly display as little or as much information by clicking the level symbols to the left of your worksheet.


Conditional Formatting

Highlight cell values for maximum data clarity.

Conditional Formatting

Conditional Formatting

The DevExpress Spreadsheet ships with Microsoft Excel inspired Conditional Formatting support. This powerful feature allows you to highlight cells based on specified criteria without writing a single line of code. Cells can be highlighted with data bars, icons and predefined color scales. At runtime, end-users can easily apply style conditions by activating the Spreadsheet’s popup menu.


Sort Data

Sort data against an unlimited number of columns.

Sort Data

As you would expect, our VCL Spreadsheet supports sorting against an unlimited number of columns. You can sort data by text (alphabetically, according to the current culture), numbers, dates and time.


Functions

Numerous built-in functions and operators (mathematical, statistical, financial, logical, etc).

Functions

Functions

Numerous built-in functions and operators (mathematical, statistical, financial, logical, etc.) allow you to enter formulas and perform calculations of any complexity.

The VCL Spreadsheet API allows you to create your own functions. Custom functions are available for all spreadsheet calculations, and can be used in formulas. Custom functions are not saved in a workbook file, and should be added in code.


Text Search & Highlighting

Find / Replace

Text Search & Highlighting

Text Search & Highlighting

A simple and quick way to find cell values. The ‘Find and Replace’ dialog removes all complexities associated with data searching. This dialog allows users to enter a search string and initiate a search against all values displayed in the worksheet.


Try It Now!

Download our fully-functional 30-day trial today and
experience the DevExpress difference today.

 

Free 30 Day TrialDemos

The most powerful VCL Data Grid

The most popular data grid for the VCL platform is only available from DevExpress. From standard two-dimensional tables to runtime grouping and column customization; from master-detail relationships to card views; from integrated themes to unbound mode… The DevExpress VCL Grid Suite is the industry standard, without equal in the marketplace. Read about VCL Data Grid

Straightforward Localization

DevExpress VCL Subscriptions ship with a localization component and a standalone Localizer Application, which allows end-users to generate translations for individual components. A number of ready-to-use translations have been published and can be downloaded via the DevExpress Support Center.
Search the Support Center

The richest collection of VCL Data Editors

From masked data input and built-in data validation to HTML formatting, the VCL Data Editors Library offers unmatched data editing options whether used for standalone data editing or as cell editors in container controls like the DevExpress VCL Data Grid.
Read about VCL Data Editors

The easy-to-use VCL Reporting

Render and print your UI without writing a single line of code and deliver a nearly unlimited set of reports without using a banded report designer.

VCL Themes and App Skins

The DevExpress VCL Subscription ships with over 40 custom-designed and highly-polished themes for your next Delphi & C++Builder application.

Built-in, easy-to-use Application Templates

The DevExpress VCL Subscription includes a series of application templates so you can hit the ground running and create application shells that mimic some of today’s most popular applications.

What’s New

уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.

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

Введение

Итак, цель сегодняшней статьи — поделиться с Вами опытом работы с Microsoft Excel в приложениях, написанных на Delphi.
Вспомнился сейчас один случай. Когда я только начинал работать по своей специальности, пригласили меня написать программу-расчётник для экологов нашего нефтезавода. В принципе ничего серьёзного — программа считает выброс от нагревательной печи и выдает табличку результатов, которую необходимо распечатать и уложить в толстую папку с отчётами. Естественно, что в области разработки подобных приложения я далеко не пионер, поэтому дали взглянуть на аналог будущей программы, который работал ещё под DOS и печатались отчёты на дико скрипящем матричном принтере с 12-ю иголками. Ну посмотрел, элементарная таблица, расчёт немного запутан, но жить можно — начал по-тихоньку писать. И попалась мне тогда на глаза статейка про работу с Excel в Delphi. Вот я и решил попробовать выдавать отчёт не только на форму приложения, а ещё и скидывать весь ход расчёта с формулами и прочим делом в Excel…Надо сказать более сильно детской радости начальника отдела я не видел до сих пор :). Люди, всю жизнь проработавшие в DOS увидели как тот же самый расчёт может выглядеть в современных условиях. Вот теперь при определении технических заданий на каждую новую программу, обязательно присутствует пункт, гласящий, что программа должна передавать данные либо в MS Word либо в MS Excel.Соответственно и цена на разработку возрастает, иногда значительно.

Отсюда можно сделать простой и однозначный вывод — заказчики готовы пожертвовать лишними деньгами только для того, чтобы всё в программе было красиво. Excel может дать вашему приложению ту самую красоту и удобство.

Ну, а для того, чтобы каждый раз не утруждать себя выполнением однотипных операций, я разработал небольшой модуль для работы с Excel. Этот же модуль я в настоящее время дорабатываю под ещё одну задачу, но об этом после. Сегодня основы основ работы с Excel в Delphi.

Создаем новый модуль (unit) и подключаем в uses следующие модули:

uses ComObj, ActiveX, Variants, Windows, Messages, SysUtils, Classes;

теперь объявляем глобальную переменную:

Одну константу (для удобства):

const ExcelApp = 'Excel.Application';

И пишем простенькую функцию:

function CheckExcelInstall:boolean;
var
  ClassID: TCLSID;
  Rez : HRESULT;
begin
// Ищем CLSID OLE-объекта
  Rez := CLSIDFromProgID(PWideChar(WideString(ExcelApp)), ClassID);
  if Rez = S_OK then  // Объект найден
    Result := true
  else
    Result := false;
end;

Или ещё короче:

function CheckExcelInstall: boolean;
var
  ClassID: TCLSID;
begin
  Result:=CLSIDFromProgID(PWideChar(WideString(ExcelApp)), ClassID) = S_OK;
end;

Если функция CLSIDFromProgID находит CLSID OLE-объекта, то, соответственно — Excel установлен.

Но проверка на наличие установленного Excel — это только часть необходимых операций перед началом работы. Другой немаловажной проверкой является проверка на наличие уже запущенного экземпляра Excel. Если этого не делать, то может случиться такая нехорошая ситуация, когда в системе будет зарегистрировано …дцать процессов Excel и все оперативная память волшебным образом утекает «в трубу» — за такое могут и по ушам надавать. Но мы-то свои уши бережем. Пишем вторую функцию проверки.

2. Определяем запущен ли Excel

function CheckExcelRun: boolean;
begin
  try
    MyExcel:=GetActiveOleObject(ExcelApp);
    Result:=True;
  except
    Result:=false;
  end;
end;

Думаю тут лишних объяснений не потребуется? Всё предельно просто — если есть активный процесс Excel, то мы просто получаем на него ссылку и можем использовать Excel для своих корыстных целей. Главное — не забыть проверить — может кто-то этот самый Excel забыл закрыть, но это другой момент. Будем считать, что Excel в нашем полном распоряжении.

3. Как запустить Excel?

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

function RunExcel(DisableAlerts:boolean=true; Visible: boolean=false): boolean;
begin
  try
{проверяем установлен ли Excel}
    if CheckExcelInstall then
      begin
        MyExcel:=CreateOleObject(ExcelApp);
//показывать/не показывать системные сообщения Excel (лучше не показывать)
        MyExcel.Application.EnableEvents:=DisableAlerts;
        MyExcel.Visible:=Visible;
        Result:=true;
      end
    else
      begin
        MessageBox(0,'Приложение MS Excel не установлено на этом компьютере','Ошибка',MB_OK+MB_ICONERROR);
        Result:=false;
      end;
  except
    Result:=false;
  end;
end;

Здесь мы в начале проверяем, установлен ли Excel в принципе и, если он все же установлен, запускам. При этом мы можем сразу показать окно Excel пользователю — для этого необходимо выставить параметр Visible в значение True.

Также рекомендую всегда отключать системные сообщения Excel, иначе, когда программа начнет говорить голосом Excel — пользователь может занервничать.

Переходим к следующему этапу работы — созданию рабочей книги.

4. Создаем пустую рабочую книгу Excel

Для создания пустой рабочей книги я обычно использую вот такую функцию:

function AddWorkBook(AutoRun:boolean=true):boolean;
begin
  if CheckExcelRun then
    begin
      MyExcel.WorkBooks.Add;
      Result:=true;
    end
  else
   if AutoRun then
     begin
       RunExcel;
       MyExcel.WorkBooks.Add;
       Result:=true;
     end
   else
     Result:=false;
end;

Второй вариант (более лаконичный):

function AddWorkBook(AutoRun: boolean = true): boolean;
begin
  Result := CheckExcelRun;
  if (not Result) and (AutoRun) then
  begin
    RunExcel;
    Result := CheckExcelRun;
  end;
  if Result then
    MyExcel.WorkBooks.Add;
end;

То есть сразу проверяю запущен ли Excel и, если он не запущен, то либо запускаю и добавляю книгу, либо просто выхожу — всё зависит от ситуации.

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

function GetAllWorkBooks:TStringList;
var i:integer;
begin
  try
    Result:=TStringList.Create;
    for i:=1 to MyExcel.WorkBooks.Count do
      Result.Add(MyExcel.WorkBooks.Item[i].FullName)
  except
    MessageBox(0,'Ошибка перечисления открытых книг','Ошибка',MB_OK+MB_ICONERROR);
  end;
end;

Функция возвращает список TStringList всех рабочих книг Excel открытых в данный момент. Обратите внимание, что в отличие от Delphi Excel присваивает первой книге индекс 1, а не 0 как это обычно делается в Delphi при работе, например, с теми же индексами в ComboBox’ах.

Ну, и наконец, после того, как поработали с книгами — их требуется закрыть. Точнее сохранить, а потом уж закрыть.

5. Сохраняем рабочую книгу и закрываем Excel

Для того, чтобы сохранить рабочую книгу, я использовал такую функцию:

function SaveWorkBook(FileName:TFileName; WBIndex:integer):boolean;
begin
  try
    MyExcel.WorkBooks.Item[WBIndex].SaveAs(FileName);
    if MyExcel.WorkBooks.Item[WBIndex].Saved then
      Result:=true
    else
      Result:=false;
  except
    Result:=false;
  end;
end;

Если у Вас открыто 10 книг — просто вызываете функцию 10 раз, меняя значение параметра WBIndex и имени файла и дело в шляпе.

А закрывается Excel вот так:

function StopExcel:boolean;
begin
  try
    if MyExcel.Visible then MyExcel.Visible:=false;
    MyExcel.Quit;
    MyExcel:=Unassigned;
    Result:=True;
  except
    Result:=false;
  end;
end;

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

Книжная полка

Название:Разработка приложений Microsoft Office 2007 в Delphi

Описание Описаны общие подходы к программированию приложений MS Office. Даны программные методы реализации функций MS Excel, MS Word, MS Access и MS Outlook в среде Delphi.

купить книгу delphi на ЛитРес

5
3
голоса

Рейтинг статьи

уважаемые посетители блога, если Вам понравилась, то, пожалуйста, помогите автору с лечением. Подробности тут.

Пример размещения Delphi компонента

A7rexcel это компонент формирования отчетов в Excel для Delphi 7Delphi XE2 (Embarcadero RAD Studio XE2). Компонент полностью бесплатен и свободен для использования где угодно и как угодно, единственная просьба — ссылка на этот сайт при упоминании этого компонента на просторах интернета.

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

Результат работы Delphi компонентаA7rexcel  позволяет выводить информацию в Excel используя в качестве шаблона xls-файл, благодаря чему становится просто настроить внешний вид получаемого документа, ориентацию листа, поля, нумерацию, и все остальное что можно настраивать в экселевском документе.

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

Исходные коды компонента на hithub — github.com/a7in/a7rexcel

Скачать компонент и демо-проект — a7rexcel.zip

Пример простейшего отчета:

 Компонент работает со всеми версиями офиса — 2003,2007,2010,2013.

Now write codes using above variables on a Button click or other appropriate event.

1. Create and connect with an Excel Application…

    myxlApp := TExcelApplication.Create(Nil);

    myxlApp.Connect;

    myxlApp.Visible[LCID] := True; // will show newly connected Excel application // most of case not required //

2. Close and Free the Excel application….

    myxlApp.Disconnect;

    myxlApp.Quit;

    FreeAndNil(myxlApp);

3. Add a Workbook

    myxlApp.Workbooks.Add(EmptyParam, LCID); //it will also add a default sheet to workbok//

    myxlBook := TExcelWorkbook.Create(myxlApp);

    myxlBook.ConnectTo(myxlApp.ActiveWorkbook);

4. Disconnect Workbook before close

    myxlBook.Close(True,’C:jitendraExcelTest1.xlsx’); //Saves the changes to mentioned file//

    myxlBook.Disconnect;

    FreeAndNil(myxlBook);

5. Add new Worksheet

    myxlSheet11 := TExcelWorksheet.Create(myxlBook);

    myxlSheet11.ConnectTo(myxlBook.ActiveSheet as _worksheet); //connecting with the default worksheet//

    myxlSheet11.Name := ‘Class 11’;

6. Disconnect worksheet before close

    myxlSheet11.Disconnect;

    FreeAndNil(myxlSheet11);

7. Adding a new Worksheet to the Workbook

myxlBook.Worksheets.Add(EmptyParam, EmptyParam, EmptyParam, EmptyParam, LCID);

    myxlSheet12 := TExcelWorksheet.Create(myxlBook);

    myxlSheet12.ConnectTo(myxlBook.ActiveSheet as _worksheet);

    myxlSheet12.Name := ‘Class 12’;

8. Access Sheets by Index or Name

(myxlApp.Worksheets[0] as _Worksheet).Activate(LCID);

Or

(myxlApp.Worksheets[‘Sheet1’] as _Worksheet).Activate(LCID);

9. Assign values to Cell by using Cell or Range property

    myxlApp.Cells.Item[1,1] := ‘Value 1’; //with row, col number//

    myxlApp.Range[‘A3′,’A3’].Value := ‘value 2’; //with cell from, to names//

    myxlSheet11.Cells.Item[1,5] := ‘JITENDRA’; //with row, col number//

    myxlSheet11.Range[‘E3′,’E3’].Value := ‘7834911261’; //with cell from, to names//

10. Change font format of an Excel Range

    with myxlSheet11.Range[‘A1’, ‘B3’] do

    begin

      Font.Name := ‘Verdana’;

      Font.Size := 15;

      Font.Bold := True;

      Font.Strikethrough := True;

      Font.Color := clRed;

    end;

11. Change Background Color of cells

    with myxlSheet11.Range[‘A1’, ‘A1’].Interior.Color := clYellow;

myxlSheet11.Range[‘A5’, ‘D7’].Merge(False);// merge cells and fill color in merged cells//

myxlSheet11.Range[‘A5’, ‘D7’].Interior.Color := clRed;

12. Merge Cells in a range

    myxlSheet11.Range[‘A5’, ‘D7’].Merge(False); //False by default if True it would merge cells row by row//

    myxlSheet11.Range[‘A5’, ‘D7’].Value := ‘Merged data’;

13. Change Column width and Row height

    myxlSheet11.Range[‘B5’, ‘B5’].ColumnWidth := 5; //single column B//

    myxlSheet11.Range[‘J5’, ‘L8’].ColumnWidth := 15; //multiple column J,K,L//

    myxlSheet11.Range[‘B5’, ‘B5’].RowHeight := 50; //single row 5//

    myxlSheet11.Range[‘J10’, ‘J15’].RowHeight := 50; //multiple row 10-15//

14. Open the workbook that already exists: 

myxlApp.Workbooks.Open ( ‘C:jitendraExcelTest1.xlsx’

EmptyParam , EmptyParam , EmptyParam , EmptyParam ,

EmptyParam , EmptyParam , EmptyParam , EmptyParam ,

EmptyParam , EmptyParam , EmptyParam , EmptyParam , 0 );

15. Copy and Paste Data from one cell to another in same sheet…

a. 

myxlSheet11.UsedRange[LCID].Copy(myxlSheet11.Range[‘J10’, ‘J10’]);

myxlSheet11.Range[‘A5’, ‘D7’].Copy(myxlSheet11.Range[‘J10’, ‘J10’]);

b. 

       myxlSheet11.UsedRange[LCID].Copy(EmptyParam);

       myxlSheet11.Range[‘J10’, ‘J10’].PasteSpecial(xlPasteAll,                xlPasteSpecialOperationNone, EmptyParam, EmptyParam);

myxlSheet11.Range[‘A5’, ‘D7’].Copy(EmptyParam);

    myxlSheet11.Range[‘J10’, ‘J10’].PasteSpecial(xlPasteAll, xlPasteSpecialOperationNone, EmptyParam, EmptyParam);

16. Copy and Paste Data from one Sheet to another sheet.

a. 

myxlSheet11.UsedRange[LCID].Copy(myxlSheet12.Range[‘J10’, ‘J10’]);

myxlSheet11.Range[‘A5’, ‘D7’].Copy(myxlSheet12.Range[‘J10’, ‘J10’]);

b. 

    myxlSheet11.UsedRange[LCID].Copy(EmptyParam);

    myxlSheet12.Range[‘J10’, ‘J10’].PasteSpecial(xlPasteAll, xlPasteSpecialOperationNone,EmptyParam, EmptyParam);

myxlSheet11.Range[‘A5’, ‘D7’].Copy(EmptyParam);

    myxlSheet12.Range[‘J10’, ‘J10’].PasteSpecial(xlPasteAll, xlPasteSpecialOperationNone,EmptyParam, EmptyParam);

17. Insert new columns before b1

myxlSheet11.Range[‘b1’, ‘b1’].Columns.Insert(xlShiftToRight); // we can use xlShiftToLeft//

18. Insert new rows above b2

myxlSheet11.Range[‘b2’, ‘b2’].Rows.Insert(xlShiftDown); // we can use xlShiftUp//

19. Clear a Selected Range Content or Format

    myxlSheet11.Range[‘b3’, ‘b10’].ClearContents;

    myxlSheet11.Range[‘b3’, ‘b10’].ClearFormats;

20.Save, Save as a Sheet / Workbook

  myxlSheet11.SaveAs(‘Filename’);

    myxlBook.Save;

21. Print Preview / Print of a Sheet / Workbook

    myxlSheet11.PrintPreview;

    myxlSheet11.PrintOut;

    myxlBook.PrintPreview;

    myxlBook.PrintOut;

22. Set Sheet PageSetup

myxlSheet11.PageSetup.

A. header: 

myxlSheet11.PageSetup.CenterHeader := » The report shows » ;

B. footer: 

myxlSheet11.PageSetup.CenterFooter := » The & P » ;

The C. header into the top margin 2cm: 

myxlSheet11.PageSetup.HeaderMargin := 2 / 0.035 ;

D. footer bottom margin 3cm: 

myxlSheet11.PageSetup.HeaderMargin := 3 / 0.035 ;

E. top margin 2cm: 

myxlSheet11.PageSetup.TopMargin := 2 / 0.035 ;

The bottom edge of the f. from the 2cm: 

myxlSheet11.PageSetup.BottomMargin := 2 / 0.035 ;

G. left 2cm: 

myxlSheet11.PageSetup.LeftMargin := 2 / 0.035 ;

On the right side of the H. from the 2cm: 

myxlSheet11.PageSetup.RightMargin := 2 / 0.035 ;

I. pages horizontally: 

myxlSheet11.PageSetup.CenterHorizontally := 2 / 0.035 ;

The J. page vertically: 

myxlSheet11.PageSetup.CenterVertically := 2 / 0.035 ;

K. print cell line: 

myxlSheet11.PageSetup.PrintGridLines := True ;

23. Auto Fill of Range. Fills value 1-10 in p1:p10

    myxlSheet11.Range[‘p1’, ‘p1’].Value := 1;

    myxlSheet11.Range[‘p2’, ‘p2’].Value := 2;

    myxlSheet11.Range[‘p1’, ‘p1’].AutoFill(myxlSheet11.Range[‘p1’, ‘p10’], xlFillSeries);

Other fill options

  xlFillCopy 

  xlFillDays 

  xlFillDefault 

  xlFillFormats 

  xlFillMonths 

  xlFillSeries 

  xlFillValues 

  xlFillWeekdays 

  xlFillYears 

  xlGrowthTrend 

  xlLinearTrend 

24. Change Border style of cells in a range

    myxlSheet11.Range[‘p3’, ‘p4’].Borders.Color := clRed;

    myxlSheet11.Range[‘p3’, ‘p4’].Borders.LineStyle := xlDouble;

    myxlSheet11.Range[‘p3’, ‘p4’].Borders.Item[xlEdgeLeft].Color := clBlue;

    myxlSheet11.Range[‘p3’, ‘p4’].Borders.Item[xlEdgeRight].Color := clBlue;

    Other line styles.

xlContinuous 

xlDash 

xlDashDot 

xlDashDotDot 

xlDot 

xlDouble 

xlSlantDashDot 

xlLineStyleNone

25. Fill pattern style of cells in a range

    myxlSheet11.Range[‘p3’, ‘p4’].Interior.Pattern := xlPatternCrissCross;

    myxlSheet11.Range[‘p3’, ‘p4’].Interior.PatternColor := clBlue;

      Other pattern styles

xlPatternAutomatic

xlPatternChecker 

xlPatternCrissCross 

xlPatternDown 

xlPatternGray16 

xlPatternGray25

xlPatternGray50

xlPatternGray75 

xlPatternGray8 

xlPatternGrid

xlPatternHorizontal 

xlPatternLightDown 

xlPatternLightHorizontal 

xlPatternLightUp 

xlPatternLightVertical 

xlPatternNone 

xlPatternSemiGray75 

xlPatternSolid 

xlPatternUp 

xlPatternVertical

26. Add calculation function SUM/AVG/MAX/COUNT etc..

    myxlSheet11.Range[‘k1’, ‘k1’].Formula := ‘=Sum(p3:p8)’;

    myxlSheet11.Range[‘k3’, ‘k3’].Formula := ‘=Avg(p3:p8)’;

    myxlSheet11.Range[‘k5’, ‘k5’].Formula := ‘=Max(p3:p8)’;

    myxlSheet11.Range[‘k7’, ‘k7’].Formula := ‘=Count(p3:p8)’;

Понравилась статья? Поделить с друзьями:
  • Дошкольная программа скачать word
  • Дошел до конца excel
  • Доходы расходы фирмы excel
  • Доходы расходы в excel простейшая
  • Доходы полученные в excel