It’s long time since I used Delphi, but recently I’ve got the chance to do that ![]()
Began from the asking how the way Delphi accesses excel file, then eventually I tried to make it.
Not too bad, as starting from internet I got reference directly from microsoft site, but the example only shows how to automate excel to create a new workbook, whereas I need the inverse, which is slow to find the examples ![]()
Finally, from that example and knowledges I’ve had, and partially any similar examples from internet I collected, I started to type the inverse from that example.
Below is the script I made as function form. That function will give back the result to TStringGrid, but ofcourse can be modified as needed. I used Borland Delphi 6.0 and have Microsoft Excel 2003 installed at my computer.
function GiveRowHeader(x: Integer): String;
begin
if(x > 26) then Result := GiveRowHeader(x div 26) + GiveRowHeader(x mod 26)
else Result := Chr( Ord( 'A' ) + x - 1 );
end;
procedure LoadFromXLFile(AFileName: String; ASheetNum: Integer;
AStringGrid: TStringGrid; var OSheetName: String);
var
ARow, ACol: Integer;
i, j: Integer;
XLApp, XLBook, XLSheet: Variant;
begin
// Create OLE Object to Excel Application
XLApp := CreateOleObject('Excel.Application');
// Hide the Excel
XLApp.Visible := False;
// Open file
XLApp.Workbooks.Open(AFileName,
EmptyParam, //UpdateLinks: OleVariant
EmptyParam, //ReadOnly: OleVariant
EmptyParam, //Format: OleVariant
EmptyParam, //Password: OleVariant
EmptyParam, //WriteResPassword: OleVariant
EmptyParam, //IgnoreReadOnlyRecommended: OleVariant
EmptyParam, //Orign: OleVariant
EmptyParam, //Delimiter: OleVariant
EmptyParam, //Editable: OleVariant
EmptyParam, //Notify: OleVariant
EmptyParam, //Converter: OleVariant
EmptyParam, //AddToMru: OleVariant
0
);
XLBook := XLApp.ActiveWorkbook;
XLSheet := XLBook.WorkSheets[ASheetNum];
XLSheet.Activate;
XLSheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
OSheetName := XLSheet.Name;
// Get last row value
ARow := XLApp.ActiveCell.Row;
AStringGrid.RowCount := ARow + 1;
// Get rightmost column value
ACol := XLApp.ActiveCell.Column;
AStringGrid.ColCount := ACol + 1;
// Doing something with the content
for i := 1 to ARow do
begin
AStringGrid.Cells[0, i] := IntToStr(i);
for j := 1 to ACol do
begin
AStringGrid.Cells[j, 0] := GiveRowHeader(j);
AStringGrid.Cells[j, i] := XLSheet.Cells[i, j];
end;
end;
// Then exit the Excel if done
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False; // disable any alert from the Excel
XLApp.Quit; // now quit
XLApp := Unassigned; // then unassign all OLE Object has been created
XLBook := Unassigned;
XLSheet := Unassigned;
end;
end;
Remember to add Excel2000 in uses, since xlCellTypeLastCell is defined inside that unit.
uses Excel2000;
Successfully wrote down that function, this is not enough if we don’t give export functionality to my new application I’ve just made. Neither to export just to plain text file, I decided to add it export to MySQL db functionality… ![]()
So, below I added for that purpose, which action is run when Button3 is clicked. In addition I used Memo1 for log progress status.
procedure TForm1.Button3Click(Sender: TObject);
var StrSQL, TableName: String;
RetVal, ARow, ACol: Integer;
begin
Memo1.Clear;
// Try to connect to MySQL Server
mysql_connect(@mysqlrec, PChar('localhost'), PChar('username'), PChar('password'));
if mysqlrec._net.last_errno = 0 then
begin
Memo1.Lines.Add('STATUS: Successfully connected to MySQL Server');
Connected := 1;
end
else
Memo1.Lines.Add('ERROR: ' + Trim(mysqlrec._net.last_error) +
' [Kode: '+IntToStr(mysqlrec._net.last_errno)+']');
// Try to attach to the database, create if not exists
mysql_query(@mysqlrec,
PChar('CREATE DATABASE /*!32312 IF NOT EXISTS*/ `test_nuedcsoft` ' +
'/*!40100 DEFAULT CHARACTER SET latin1 */;'));
Memo1.Lines.Add('QUERY: CREATE DATABASE /*!32312 IF NOT EXISTS*/ `test_nuedcsoft` '+
'/*!40100 DEFAULT CHARACTER SET latin1 */;');
RetVal := mysql_select_db(@mysqlrec, PChar('test_nuedcsoft'));
if RetVal <> 0 then
Memo1.Lines.Add('ERROR: Error attaching to database `test_nuedcsoft` '+
'[Kode: '+IntToStr(RetVal)+']' )
else
Memo1.Lines.Add('STATUS: Successfully attached to database `test_nuedcsoft`');
TableName := StringReplace(LowerCase(Trim(Edit2.Text)), ' ', '_', [rfReplaceAll]);
// First make sure to insert from the start, by delete the table
mysql_query(@mysqlrec, PChar('DROP TABLE IF EXISTS `' + TableName + '`;'));
Memo1.Lines.Add('QUERY: DROP TABLE IF EXISTS `' + TableName + '`;');
// Then re-create the table
StrSQL :=
'CREATE TABLE `' + TableName + '` (' +
'`Id` smallint(5) unsigned NOT NULL default ''0'',';
for ACol := 1 to StringGrid1.ColCount - 1 do
StrSQL := StrSQL + '`' + LowerCase(GiveRowHeader(ACol)) +
'` varchar(200) default NULL,';
StrSQL := StrSQL + 'PRIMARY KEY (`Id`)' +
' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;';
mysql_query(@mysqlrec, PChar(StrSQL));
Memo1.Lines.Add('QUERY: '+StrSQL);
// Start to insert the data
for ARow := 1 to StringGrid1.RowCount - 1 do
begin
StrSQL := 'INSERT INTO `' + TableName + '` (`Id`';
for ACol := 1 to StringGrid1.ColCount - 1 do
StrSQL := StrSQL + ',`' + LowerCase(GiveRowHeader(ACol)) + '`';
StrSQL := StrSQL + ' ) VALUES (' + IntToStr(ARow);
for ACol := 1 to StringGrid1.ColCount - 1 do
StrSQL := StrSQL + ',''' + StringGrid1.Cells[ACol, ARow] + '''';
StrSQL := StrSQL + ');';
Memo1.Lines.Add('QUERY: '+StrSQL);
mysql_query(@mysqlrec, PChar(StrSQL));
end;
// Disconnected from MySQL Server
mysql_close(@mysqlrec);
Memo1.Lines.Add('STATUS: Disconnected from MySQL Server');
Connected := 0;
end;
Before, I defined global variables first for that needed above implementation declaration.
var
Form1: TForm1;
mysqlrec: mysql; //Global mysql struct
Connected: Integer = 0; //Global var to keep track of whether mysql is connected
implementation
{$R *.dfm}
I used Simple MySQL Delphi Connection library for that to be done, so I defined that unit in uses.
uses _libmysq;
Done! Now my application has Import from Excel and Export to MySQL ability. ![]()
P.S.:
If you need that project’s source code, I am willing to email you just for free.
July 26th, 2007 at 04:37:34
I just want to say thank you.
I was trying to open and manipulate an excel file from Delphi, and I didn’t find much information.
Your entry was really helpful, and I finally solved my problem.
THANKS!!!
October 30th, 2007 at 11:24:37
Hi, i need project’s source code for my task in collage.
thanks.
January 11th, 2008 at 09:43:18
Thanks, it’s great tutorial, it’s really helpfull for me, but i got problems here, i’ve googling and didn’t found “I used Simple MySQL Delphi Connection library for that to be done, so I defined that unit in uses.” may the library mailed to me? it’s will satisfied me if you mailed the complete source code too.
best regard;
matur nuwun bro.
hidup indonesia.
selamat tahun baru
ahlan wah sahlan
January 15th, 2008 at 04:11:46
Hi, i need project’s source code for my task in collage.”Excel to Delphi to MySQL db”
thanks.
January 15th, 2008 at 11:10:07
I already sent the source code as requested. Hope this will helpful.:-)
But for arif,.. when I sent to you, it was failed. I tried twice but failure notice always gives me this message:
—- (1) truncated message
64.233.171.27 failed after I sent the message.
Remote host said: 552 5.7.0 Illegal Attachment a45si9746670rne.10
—- (2) truncated message
66.249.83.27 failed after I sent the message.
Remote host said: 552 5.7.0 Illegal Attachment h38si25569754wxd.15
—- truncated message
I have no idea what it means, or maybe you need to tell me your another correct email. Thx.
Obviously, since in this blog (wordpress.com) I can not upload for zip or exe filetype (to make download link) so that is why I send the source code one-by-one as request.
But this not helpful too much since I can not always stand by all the time,.. Maybe if someone knows where I can share my source code I will glad to know that.
I’ve tried rapidshare, but it has expiration on upload and it has limitation on download. In meanwhile, please be patiant if I can not give response as quick.
April 11th, 2008 at 02:04:46
Hi, i need project’s source code, please can you send me. Thx.
May 8th, 2008 at 12:56:56
Hi i need to know on how to use mysql as a back end to delphi. tanx
June 8th, 2008 at 16:00:14
hello i’m very interested in your source code for doing this. I need to do something similar in a little project of mine.
peace
dj sinae
June 17th, 2008 at 03:24:50
hello i am very impress about your project could i have the full source code please
June 18th, 2008 at 09:32:02
dj sinae,
I sent to you only the source code without the exe-compiled since Gmail doesn’t allow executable files in attachment
http://mail.google.com/support/bin/answer.py?answer=6590
You can compile by your self and I using Borland Delphi 6.0 to do this.
Hope this is helpful.
peace
August 15th, 2008 at 23:10:32
Hi
It looks interesting and will be usefull in a project I’m working on.
I would very much have your sourcecode.
Thanks.
August 26th, 2008 at 21:52:13
Hi Yayak! Very helpful code, thank you! I’ll be grateful if you could send me the whole code. Cheers!
September 4th, 2008 at 03:28:42
I would very much have your sourcecode.
September 16th, 2008 at 17:12:10
I’m new to delphi programming though im getting along very well..i need this code please.
September 17th, 2008 at 13:06:04
Thank you vary much andriu,. I’ve already sent to Lesya and Shawn too, hope you receive it with no corrupt and useful.
best regards,
peace
September 17th, 2008 at 16:25:33
Hi, i need project’s source code, please can you send me. Thx.
September 23rd, 2008 at 12:48:00
Hi, could you show me how to copy sheet within the workbook ?
I tried using OLEObject, but no help available.
TExcelApplication litle bit better with code completion, but has no enough documentation either.
Thanks in advance and best regards.
October 15th, 2008 at 08:50:07
I’m newbie
can i get this code please.
November 6th, 2008 at 14:13:15
Hi,
I am also still newbie in Delphi programming.
Could you please send me your sourcecode?
What about if I am using MS SQL database instead of MySQL? How to do?
January 29th, 2009 at 09:15:57
Hello webmaster,
it’s great tutorial!!. I was trying to manipulate excel from delphi for long time, and never found good informations. would you please upload your complete source code to ziddu (www.ziddu.com) so We (‘Delphiers’) can download it. Thanks
August 7th, 2009 at 04:25:26
hi, yayak! I need your sourcecode.
Could you send me it please?
thanks a lot!
August 26th, 2009 at 11:15:31
i need this source import excel to mysql, could you help me to sent this your source code to my e-mail,,, please?? thax a lot before
August 26th, 2009 at 15:43:34
thanks for your great info
November 29th, 2009 at 09:30:54
Could you send me it please? thax a lot before