delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback



Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi








Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (8)


How to export a dataset to excel, without knowing VBFormat this article printer-friendly!Bookmark function is only available for registered users!
How to make the vba parameters visible
Product:
Delphi 5.x (or higher)
Category:
OLE
Skill Level:
Scoring:
Last Update:
02/14/2002
Search Keys:
delphi delphi3000 article borland vcl code-snippet TExcelapplication vbaxl8.hlp export msoffice spreadsheet
Times Scored:
9
Visits:
13159
Uploader: Steven van Els
Company: Staatsolie Refinery
Reference: Desenvolvendo Aplicacoes com Delphi 6 isbn 85-346-1387-7
 
Question/Problem/Abstract:
The end user of your (database) program, eventually wants the ability to create his own graphs with the data. In most cases they look for Excel. The programmer not familiar with VB or VBA has to learn a little of VB to acomplish this. Instead of trying to understand the vbaxl8 Help file, we can use the macro recorder to see how excell use the commands.
Answer:



There are various ways to export data, but the most efficient way is to use the objects, methods and properties from the server.
In this case TExelApplication at the Servers palette.
These informations can be found in vbaxl8.hlp (excel) or vbawrd8.hlp (word) somewhere in the office directory.
The big problem is that we have to pass all the parameters to the procedures, which are a lot, but luckily there is a way to expose the parameters, without studying the ms help files for months.
We will use the Macro Recorder and editor to retrieve all the vb ingredients



Objective: Export data from a query  (DBDEMOS table Orders.db) to excel


The query will retrieve 10 columns and the Total value of the order is greater then $15000, and write it to an Excel file.

the SQL property of the TQuery:
SELECT OrderNo, CustNo, SaleDate, EmpNo, ShipVIA, Terms, ItemsTotal, TaxRate, Freight, AmountPaid
FROM "orders.db" Orders where ItemsTotal > 15000


First we have to prepare the excel layout.

Open Excel, go to Tools --> Macro --> Record new macro

We will:
1) prepare the header with the column names
2) apply bold font, and centering
3) Fill in 2 rows of data
4) Apply the 4-mar-97 date format
5) Apply percent format
6) Apply $10,000.00 format to 3 columns
7) Use Autoformat to give some nice colors to the table
8) Show all columns with autofit

Just record the macro by typing in all the necessary stuf and formating etc. After that you use the macro editor to make command made visible.

It should look like this:
Sub ExportToExcel()
'
' ExportToExcel Macro
' Macro recorded 2/10/2002 by
    {step 1}
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "Order No"
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "Cust No"
    Range("C1").Select
    etc...
    Range("J1").Select
    ActiveCell.FormulaR1C1 = "Amount Paid"
     {step 2}
    Range("A1:J1").Select
    Selection.Font.Bold = True
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .ShrinkToFit = False
        .MergeCells = False
    End With
     {step 3}
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "100"
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "200"
    Range("C2").Select
    ActiveCell.FormulaR1C1 = "11/6/2001"
    Range("D2").Select
    ActiveCell.FormulaR1C1 = "30"
    Range("E2").Select
    ActiveCell.FormulaR1C1 = "Agent"
    Range("F2").Select
    ActiveCell.FormulaR1C1 = "Fob"
    Range("G2").Select
    etc...
    Range("H3").Select
    ActiveCell.FormulaR1C1 = "2"
    Range("I3").Select
    ActiveCell.FormulaR1C1 = "1000"
    Range("J3").Select
    ActiveCell.FormulaR1C1 = "9000"
    {step 4}
    Columns("C:C").Select
    Selection.NumberFormat = "d-mmm-yy"
    {step 5}
    Columns("H:H").Select
    Selection.NumberFormat = "0.00%"
    {step 6}
    Columns("G:G").Select
    Selection.NumberFormat = "$#,##0.00"
    Columns("I:I").Select
    Selection.NumberFormat = "$#,##0.00"
    Columns("J:J").Select
    Selection.NumberFormat = "$#,##0.00"
    {step 7}
    Range("A1:J3").Select
    Selection.AutoFormat Format:=xlRangeAutoFormatList1, Number:=True, Font:= _
        True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
    {step 8}
    Columns("C:C").EntireColumn.AutoFit
End Sub


Ingredients for delphi
1)TForm of course
2)TQuery
3)SaveDialog
5)TExcelapplication
6)bitButton
7)dbGrid, dbNavigator, datasource for comparison




procedure TForm1.bbtnExportToExcelClick(Sender: TObject);
var
LineNumber, LCID : Integer;
LineString : string;
begin
  with SaveDialog1 do
  begin
    FileName :='';
    Filter:= 'Excel files|*.XLS;All Files|*.*';
    DefaultExt := 'XLS';
    Title := 'Exporting to Excel';
    if execute then
    begin
      query1.Open;
      LCID := GetUserDefaultLCID;
      with ExcelApplication1 do
      begin
        connect;
        try
          visible[LCID] := true;
          Workbooks.Add(EmptyParam,LCID);
          
              commands found in macro
             //step 1
          Range['A1','J1'].Value := VarArrayOf(['Order No',
                'Cust No','Sale Date','Emp No',
                'Ship Via', 'Terms','Items Total',
                'Tax Rate','Freight','Amount Paid']);

            //step 2
          with Range['A1','J1']do
          begin
            HorizontalAlignment := xlcenter;
            VerticalAlignment := xlBottom;
            Wraptext := false;
            Orientation := 0;
            ShrinkTofit := false;
            MergeCells := false;
            Font.Bold := true;
          end;

          Query1.First;
          LineNumber := 1;

               //step 3, where by iteration the data from the query is transported to excell
          While not query1.Eof do
          begin
            Inc(lineNumber);
            LineString := IntToStr(LineNumber);
            Range['A'+LineString, 'J'+LineString].Value :=
              VarArrayof([Query1OrderNo.value, Query1CustNo.Value,
                             //step 4 is built in
                          FormatDateTime('d-mmm-yy',Query1SaleDate.Value),
                          Query1EmpNo.Value, Query1ShipVIA.Value,
                          Query1Terms.Value, Query1ItemsTotal.Value,
                          Query1TaxRate.Value, Query1Freight.Value,
                          Query1AmountPaid.Value]);
            Query1.Next;
          end;


          LineString := IntToStr(LineNumber);

          Range['H2','G'+LineString].NumberFormat := '0.00%';
          Range['G2','G'+LineString].NumberFormat := '$#,##0.00';
          Range['I2','I'+LineString].NumberFormat := '$#,##0.00';
          Range['J2','J'+LineString].NumberFormat := '$#,##0.00';
             //step 7
          Range['A1','J'+LineString].AutoFormat(xlRangeAutoFormatlist1, true,
                   true,true,true,true,true);
               //step 8
          Range['A1','J'+LineString].Columns.AutoFit;
            end of macro stuff


          ActiveWorkbook.SaveAs(FileName,xlNormal, '', '', false, false,
                     xlNochange,xlUserResolution,False,EmptyParam,EmptyParam,
                     LCID);
          Quit;
        finally
        disconnect;
      end;  //try
    end;  //with Excelapplication1
  end;  //if  execute
end; //with Savedialog1

end;


Comments:

Range("A1").Select
    ActiveCell.FormulaR1C1 = "Order No"

Has the equivalent in Delphi

Range['A1','A1'].select;
    ActiveCell.FormulaR1Ci := 'Order No';

But entering the cells one by one is not very efficient, that is why a variant array is used to enter the values line by line

Range['A1','J1'].Value := VarArrayOf(['Order No',
                'Cust No','Sale Date','Emp No',
                'Ship Via', 'Terms','Items Total',
                'Tax Rate','Freight','Amount Paid']);



This methodology I found in the book: Desenvolvendo Aplicacoes com Delphi 6  written by Bruno Sonnino, and adapted it to suite my needs.











Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
Update code for Delphi 2007 and office XP
    Steven van Els (Feb 19 2008 2:34PM)

Recently I detected that with Delphi 2007 and Office XP, that the command:

Range['A1', 'B2'].Value := VarArrayOf...

must be replaced by

Range['A1', 'B2'].Value2 := VarArrayOf...


Respond

old format
    Sahar Azmy (Jan 20 2008 2:24PM)

i used this code but it i have aproblem at line  Workbooks.Add(EmptyParam,LCID);
it gives me messsage of (old format or invaid library)
Respond

OK!.... Ooops!
    Rex Torres (Jul 11 2005 2:29AM)

Thanks for the piece of code. It really was a great help. I copied your code and made some little modifications for the application I'm developing. I'm developing a delphi database (Interbase) application.

There is one problem though... I get this message "Access violation at address .... Read of address ..." This happens somewhere in the ActiveWorkbook.SaveAs() method. Can you help me with this?
Respond

RE: OK!.... Ooops!
Steven van Els (Aug 10 2005 4:17AM)

If you are not sure which parameter to pass, use EmptyParam, Delphi takes care of putting a default parameter. There are some differences between the various versions of Exel, but normally a little trial and error helps.

Which version of exel gives the problem?

Regards
Respond

RE: RE: OK!.... Ooops!
Rex Torres (Aug 11 2005 6:07AM)

thanks! i'm using excel 2000...

one more question... can u use TExcelApplication to connect to (and manipulate) excel 97 (and older)?

thanks again!...
Respond

RE: RE: RE: OK!.... Ooops!
Steven van Els (Aug 12 2005 3:54AM)

Yes it can be used for exel97, in fact in Delphi 6 when installing it aks which version of office components you want to use. It makes difference in office97 and office2000
Respond

RE: RE: RE: RE: OK!.... Ooops!
Rex Torres (Aug 15 2005 11:15AM)

Thanks very much!!! (again...)
Yeah... I do remember (vaguely) I was asked about my MS Office version when I installed Delphi.

One last thing... I hope... (Annoying! am I?)

TExcelApplication supports Office 97. But, I installed Delphi specifying Office 2000 as my MS Office. Does this mean I can't make applications (that use Office) for computers that have Office 97?

I once created a test program that uses Excel. When I tried to run it in computers that have Office 97, I got an error message (forgot wat it was... something about the server refusing connection, I think).

Thanks for all your help!!!
Respond

How to
    Adriana Ivonne Espinosa Chavez (Jun 17 2003 12:03AM)

How to find more information about these instructions?.. i need. i make the program and i liked.
for you attention best regards!!!
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


   


  Community Ad of
D. Souchard
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)