Exporting a list to OpenOffice Calc from Delphi - delphi

I'm using Delphi 7 and I'd like to export the contents of a list from my program to OpenOffice Calc using automation, instead of using files.
The task is simple: create new document, iterate through rows/columns and change cell data.
I've found some code but it's not complete, and I was hoping someone has some example code ready to accomplish this very simple task. It could save me a few hours of trying.
Thanks in advance!
Edit: I'd like to automate OpenOffice Calc to achieve what I wrote above. Thanks!

The easiest solution is to write CSV file output, and open that in OpenOffice.
There are also libraries to write .XLS files which both OpenOffice Calc and Excel can read. CSV is so simple, I wonder that you need an example. Create a TStringList, and add strings to it, in comma separated format. Save to file.
The so called "programmatic" method involves OLE automation.
uses
OleAuto;
var
mgr,calc,sheets,sheet1,dt,args:Variant;
begin
args = VarArrayCreate(...);
mgr := CreateOleObject('com.sun.star.ServiceManager');
dt := mgr.createInstance('com.sun.star.frame.Desktop')
calc = dt.loadComponentFromURL('private:factory/scalc', '_blank', 0, args)
sheets = calc.getSheets()
sheet1 = sheets.getByIndex(0)
...

Open Office supports Automation
see: http://udk.openoffice.org/common/man/tutorial/office_automation.html
Open Office info for Delphi can be found at:
http://development.openoffice.org/#OLE
The site ooomacros.org seems to be down, luckily the wayback machine still has a copy:
http://replay.web.archive.org/20090608051118/http://www.ooomacros.org/dev.php
Good luck.

Related

How do I work with Word Documents without using COM Automation?

I have read multiple posts on the issue, and none seem to come to a decent conclusion to my question. (Perhaps I'm trying to see if anything has popped up lately.)
I have a small charity app that handles pledges. In doing so, it needs to work with and print documents.
Thing is, if Word is open in the background, the app thread will hang and won't respond to the closure of Word, and I have to roll back manually and close word. Sure, that all works fine, but I simply cannot guarantee that the end user will close Word, even if I put the instruction in a user manual.
I'm not too fussed about speed, but I guess that if it can be enhanced, it would be a nice little bonus.
Have any libraries been released for Delphi that will allow me to open, edit, print, and save documents? If not, is there a way to use Word Automation in such a way that it will not conflict with another open handle of Word when opened?
If you use GetActiveOleObject, you will get the running instance of Word.
By using CreateOleObject, you will get a new instance and shouldn't be troubled by other running instances.
In case you use the TWordApplication, wrapper you can set ConnectKind to ckNewInstance to accomplish this. By default, TWordApplication will try to connect with a running instance.
If you want to open edit and print Word documents and you don't mind using RTF format for what you're doing, investigate TRichView.
It will generate rich documents that are in RTF format, which is one of the formats MS word supports. I don't think it directly reads .DOC files but you can convert .DOC and .DOCX into RTF, for most simple files, but certain advanced formatting features would be lost in the conversion.
It has the advantage of working without any need for even any copy of MS Word to be installed on the machine that is going to do the document processing. For production of receipts and other simple documents, this would be the most reliable technique; Don't use Word directly, at all.
procedure PrintViaWord (const filename: string);
const
wdUserTemplatesPath = 2;
var
wrdApp, wrdDoc, wrdSel: variant;
begin
wrdApp:= CreateOleObject ('Word.Application'); // create new instance
sleep (5000); // this fixes a bug in Word 2010 to do with opening templates
wrdDoc:= wrdApp.documents.add (
wrdApp.Options.DefaultFilePath[wdUserTemplatesPath] + '\mytemplate.dot');
wrdDoc.Select;
wrdSel:= wrdApp.selection;
wrdApp.Options.CheckSpellingAsYouType:= 0;
wrdSel.paragraphformat.alignment:= 1;
wrdSel.typetext ('This is a program demonstrating how to open Word in the background'
+ ' and add some text, print it, save it and exit Word');
wrdDoc.SaveAs (filename + '.doc');
wrdApp.ActivePrinter:= 'Konica Minolta 211';
wrdApp.PrintOut;
WrdDoc.SaveAs (filename + '.doc');
wrdApp.quit;
wrdSel:= unassigned;
wrdDoc:= unassigned;
wrdApp:= unassigned
end;

openoffice calc with delphi again

I was using search engine and not just here, and got tired of it; just want a simple answer (or a link) for a simple question:
How do I open a calc sheet and write 123 into cell A1 from Delphi (7) code? (Or any hello worlds for calc?)
You can take a look at this demo:
http://sourceforge.net/projects/ooomacros/files/Delphi%20OOo/Version%201.2/Delphi_OOo_v12en.zip/download
I tested the Document part a month ago (which works), and I there is also some spreadsheet code in the examples.pas.
Ok, after some research and using the informations above for I thank yas a lot, here is a simple answer:
uses part
Uses ComObj, OOoMessages, OOoTools, OOoConstants, OOoXray;
main code
open blank document, write 'hello 123' text into a1 then save it on desktop
procedure HelloWorldExample;
var
mentesiOpciok,oSheet,oSheets,myCalc : Variant;
begin
ConnectOpenOffice;
myCalc:=StarDesktop.loadComponentFromURL('private:factory/scalc', '_blank', 0, dummyArray);
oSheets:=myCalc.getSheets;
oSheet:=oSheets.getByIndex(0);
//oSheet.getCellByPosition(0, 0).SetValue(123);
oSheet.getCellByPosition(0, 0).SetFormula('hello 123!');
mentesiOpciok:=CreateProperties(['FilterName', 'MS Excel 97']);
myCalc.storeToURL('file:///C:/Documents and Settings/Zéiksz/Asztal/calcdoc.xls', mentesiOpciok);
showMessage('kész :)');
myCalc.close(true);
DisconnectOpenOffice();
end;
use getcellbyposition(...).setvalue to set numeric values, or setformula for strings (not really sure, but there is a string in it LOL).
Péter
edit: most useful information I found on the Internet is in this forum:
http://www.oooforum.org/forum/viewtopic.phtml?t=4996

Use SSL with Delphi yet still having a single exe

We use Indy and we need SSL eMail support in our app., however we need to have our application in a single .Exe.
We know that the default Indy handler requires to have the dlls in the path. Extracting the Dlls from one of the EXE's resources would be the last resort.
Any better ideas?
Try SSLBlackBox.
TOndrey gave you a good answer. I use SecureBlackBox as well.
You may consider some other third party components:
StreamSec
SecureBridge from DevArt
Be aware: if you add SSL/TLS support inside your executable, it might become restricted for export. If you're in the USA, this could mean that your application cannot be sold or given to people outside the USA. This is why these DLL's aren't part of Indy or Delphi themselves.
The libraries that Delphi uses are actually compiled DLL's from the OpenSSL project. But if you have a good knowledge of C then you should be able to compile the source to .obj files and link them with your Delphi code instead. You would probably need to modify part of the Indy code for this too. Of course, others could have done this too, but that makes the export of those Indy components (or even Delphi itself) more complex, because of those export restrictions.
Funnily enough, source code is protected by the first amendment which basically allows you to print the code in a book and then send it to some rogue nation. While if you'd send it in digital form (compiled or not) then you're committing a federal offence and probably will have to be careful when picking up the soap in the shower for at least a year... No one claimed that laws make sense. They can just be a pain in the [beep]...
Other SSL solutions don't work together with the Indy components, which would mean you'd have to rewrite part of your code to support those other solutions.
This link tells how you can load a DLL from memory, so you don't need to have it on disk. It's an alternate solution which I haven't tried. I don't think it will work, since the two DLL's depend on each other, but it might be worth a try...
Is the "Single EXE" requirement for distribution purposes or must it also be a single .EXE file when running on the client's machine?
If it's only for distribution purposes, you can append the DLL files to the end of your .EXE file and then - when the program starts - extract them from the .EXE file and store them locally as .DLL files, something like this:
VAR F,O : FILE;
VAR BUF : ARRAY[1..<MaxSizeOfDLLs>] OF BYTE;
ASSIGN(F,ParamStr(0)); RESET(F,1);
SEEK(F,<OriginalExeSize>);
BLOCKREAD(F,BUF,<FirstDllSize>);
ASSIGN(O,<NameOfFirstDLL>); REWRITE(O,1);
BLOCKWRITE(O,BUF,<FirstDllSize>); CLOSE(O);
BLOCKREAD(F,BUF,<SecondDllSize>);
ASSIGN(O,<NameOfSecondDLL>); REWRITE(O,1);
BLOCKWRITE(O,BUF,<SecondDllSize>); CLOSE(O);
SEEK(F,<OriginalExeSize>); TRUNCATE(F); CLOSE(F)
Quick'n'Dirty, not properly formatted, etc., but should give you the basic idea.
Have you tried compiling the OpenSLL source yourself and importing the object files into Delphi?
Recommended reading: Using C object files in Delphi - explains how to create a program that does not need a DLL, and can be deployed in one piece
I use Microsoft's CAPICOM for SSl3 and it solved my needs... It's freely redistributable but discontinued
If you try other components maybe you should look to SYNAPSE(at http://synapse.ararat.cz/) (I also use) it can work with StreamSec(and others) to send emails over ssl. Its free and easy to work.
Const
cdoSendUsingMethod = 'http://schemas.microsoft.com/cdo/configuration/sendusing';
cdoSMTPServer = 'http://schemas.microsoft.com/cdo/configuration/smtpserver';
cdoSMTPServerPort = 'http://schemas.microsoft.com/cdo/configuration/smtpserverport';
cdoSendServerPort = '25';
cdoSendUsingPort = 2;
cdoSMTPConnectionTimeout = 'http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout';
cdoSMTPAuthenticate = 'http://schemas.microsoft.com/cdo/configuration/smtpauthenticate';
cdoAnonymous = '0';
cdoBasic = '1';
cdoSMTPUseSSL = 'http://schemas.microsoft.com/cdo/configuration/smtpusessl';
cdoSendUserName = 'http://schemas.microsoft.com/cdo/configuration/sendusername';
cdoSendPassword = 'http://schemas.microsoft.com/cdo/configuration/sendpassword';
cdoURLGetLatestVersion = 'http://schemas.microsoft.com/cdo/configuration/urlgetlatestversion';
...
function SensCDOMail (ASubject, AFrom, ATo, ABody, ASmtpServer : WideString): String;
var
cdoMessage:OleVariant;
cdoConfiguration: OleVariant;
begin
//Configuration Object
cdoMessage:= CreateOleObject('CDO.Message');
cdoConfiguration:= CreateOleObject('CDO.Configuration');
try
cdoConfiguration.Fields(cdoSendUsingMethod):= cdoSendUsingPort;
cdoConfiguration.Fields(cdoSMTPServer):= ASmtpServer;
cdoConfiguration.Fields(cdoSMTPServerPort):= cdoSendServerPort;
cdoConfiguration.Fields(cdoSMTPAuthenticate):= cdoAnonymous;
cdoConfiguration.Fields(cdoSMTPUseSSL ):= True; // use SSL
cdoConfiguration.Fields.Update;
cdoMessage.Configuration:= cdoConfiguration;
cdoMessage.To := ATo;
cdoMessage.From := AFrom;
cdoMessage.Subject := ASubject;
//cdoMessage.HTMLBody := ABody; //Want to send in Html format
cdoMessage.TextBody := ABody; //Want to send in text format
cdoMessage.Send;
finally
VarClear(cdoMessage);
VarClear(cdoConfiguration);
end;
end;
It is possible to include these DLLs into the program's executable as resources and either export them to files when used or even use them without exporting them first by relocating the code and searching the entry points in memory. I have got code somewhere for doing the latter....

any functions to create zip file of directory/file on vista with delphi 2009

I am looking for a simple method of zipping and compressing with delphi. I have already looked at the components at torry delphi:http://www.torry.net/pages.php?s=99. They all seem as though they would accomplish what I want however a few disadvantages to using them is that none of them run in delphi 2009 and are very complex which makes it difficult for me to port them to delphi 2009. And besides, the documentation on them is scarce, well at least to me. I need basic zipping functionality without the overhead of using a bunch of DLLs. My quest lead me to FSCTL_SET_COMPRESSION which I thought would have settled the issue but unfortunately this too did not work. CREATEFILE looked promising, until I tried it yielded the same result as FSCTL_SET... I know that there are some limited native zipping capability on windows. For instance if one right clicks a file or folder and selects -> sendTo ->zipped folder, a zipped archive is smartly created. I think if I was able to access that capability from delphi it will be a solution. On a side issue, does linux have its own native zipping functions that can be used similar to this?
TurboPower's excellent Abbrevia can be downloaded for D2009 here, D2010 support is underway and already available in svn according to their forum.
Abbrevia used to be a commercial (for $$$) product, which means that the documentation is quite complete.
I use Zipforge. Why are there problems porting these to D2009? Is it because of the 64bit??
Here is some sample code
procedure ZipIt;
var
Archiver: TZipForge;
FileName: String;
begin
try
Archiver:= TZipForge.create(self);
with Archiver do begin
FileName := 'c:\temp\myzip.zip';
// Create a new archive file
OpenArchive(fmCreate);
// Set path to folder with some text files to BaseDir
BaseDir := 'c:\temp\';
// Add all files and directories from 'C:\SOURCE_FOLDER' to the archive
AddFiles('myfiletozip.txt');
// Close the archive
CloseArchive;
end;
finally
Archiver.Free;
end;
end;
If you can "do" COM from Delphi, then you can take advantage of the built-in zip capability of the Windows shell. It gives you good basic capability.
In VBScript it looks like this:
Sub CreateZip(pathToZipFile, dirToZip)
WScript.Echo "Creating zip (" & pathToZipFile & ") from folder (" & dirToZip & ")"
Dim fso
Set fso= Wscript.CreateObject("Scripting.FileSystemObject")
If fso.FileExists(pathToZipFile) Then
WScript.Echo "That zip file already exists - deleting it."
fso.DeleteFile pathToZipFile
End If
If Not fso.FolderExists(dirToZip) Then
WScript.Echo "The directory to zip does not exist."
Exit Sub
End If
NewZip pathToZipFile
dim sa
set sa = CreateObject("Shell.Application")
Dim zip
Set zip = sa.NameSpace(pathToZipFile)
WScript.Echo "opening dir (" & dirToZip & ")"
Dim d
Set d = sa.NameSpace(dirToZip)
For Each s In d.items
WScript.Echo s
Next
' http://msdn.microsoft.com/en-us/library/bb787866(VS.85).aspx
' ===============================================================
' 4 = do not display a progress box
' 16 = Respond with "Yes to All" for any dialog box that is displayed.
' 128 = Perform the operation on files only if a wildcard file name (*.*) is specified.
' 256 = Display a progress dialog box but do not show the file names.
' 2048 = Version 4.71. Do not copy the security attributes of the file.
' 4096 = Only operate in the local directory. Don't operate recursively into subdirectories.
WScript.Echo "copying files..."
zip.CopyHere d.items, 4
' wait until finished
sLoop = 0
Do Until d.Items.Count <= zip.Items.Count
Wscript.Sleep(1000)
Loop
End Sub
COM also allws you to use DotNetZip, which is a free download, that does password-encrypted zips, zip64, Self-extracting archives, unicode, spanned zips, and other things.
Personally I use VCL Zip which runs with D2009 and D2010 perfectly fine. it does cost $120 at the time of this post but is very simple, flexible and most of all FAST.
Have a look at VCLZIP and download the trail if your interested
code wise:
VCLZip1.ZipName := ‘myfiles.zip’;
VCLZip1.FilesList.add(‘c:\mydirectory\*.*’);
VCLZip1.Zip;
is all you need for a basic zip, you can of course set compression levels, directory structures, zip streams, unzip streams and much more.
Hope this is of some assistance.
RE
Take a look at this OpenSource SynZip unit. It's even faster for decompression than the default unit shipped with Delphi, and it will generate a smaller exe (crc tables are created at startup).
No external dll is needed. Works from Delphi 6 up to XE. No problem with Unicode version of Delphi. All in a single unit.
I just made some changes to handle Unicode file names inside Zip content, not only Win-Ansi charset but any Unicode chars. Feedback is welcome.

How to write a simple .txt content processor in XNA?

I don't really understand how Content importer/processor works in XNA.
I need to read a text file (Content/levels/level1.txt) of the form:
x x
x x
x x
where x's are just integers, into an int[,] array.
Any tips on writting a SIMPLE .txt importer??? By searching google/msdn I only found .x/.fbx file importer examples. And they seem too complicated.
Do you actually need to process the text file? If not, then you can probably skip most of the content pipeline.
Something like:
string filename = "Content/TextFiles/sometext.txt";
string path = Path.Combine(StorageContainer.TitleLocation, filename);
string lineOfText;
StreamReader sr = new StreamReader(path);
while ((lineOfText = sr.ReadLine()) != null)
{
// do something
}
Also, be sure to set the "Build Action" to "None" and the "Copy to Output Directory" to "Copy if newer" on the text files you've added. This tells the content pipeline not to compile the text file but rather copy it to the output directory for use as is.
I got this (more or less) from the RacingGame sample provided by Microsoft. It foregoes much of the content pipeline and simply loads and processes text files (XML) for much of its level data.
XNA 4.0 uses
System.IO.Stream stream = TitleContainer.OpenStream("tilename.txt");
See http://msdn.microsoft.com/en-us/library/bb199094.aspx and also http://blogs.msdn.com/b/shawnhar/archive/2010/12/09/reading-files-in-xna-game-studio-4-0.aspx
There doesn't seem to be a lot of info out there, but this blog post does indicate how you can load .txt files through code using XNA.
Hopefully this can help you get the file into memory, from there it should be straightforward to parse it in any way you like.
XNA 3.0 - Reading Text Files on the Xbox
http://www.ziggyware.com/readarticle.php?article_id=69 is probably a good place to start. It covers creating a basic content processor.

Resources