OO-Snippets: Mail Merge

Commons

Keywordsmail merge
LanguageooRexx
ApplicationWriter
AuthorsMatthias Prem (initial)
Supported Versions2.0.x  
Supported OSAll  
QuestionHow can I perform a mail merge?

Assuming, you have two files: addresses.ods (with the contacts) and

letter.odt (with the letter).

Answer

Code-Snippet-Listing (snippet-source)

/* MailMerge.rex */
/* run from command line */
/* runs a MailMerge using an existing *.ods file */

/* get the desktop and a component loader */
oDesktop = UNO.createDesktop()
xComponentLoader = oDesktop~XDesktop~XComponentLoader


/* open Calc and get first sheet in spreadsheet */
url = "file:///c:/addresses.ods"
xCalcComponent = xComponentLoader~loadComponentFromURL(url, "_blank", 0, .UNO~noProps)
xSheet=xCalcComponent~XSpreadSheetDocument~getSheets~XIndexAccess~getByIndex(0)~XSpreadSheet

/* open a blank document in Writer */
url= "private:factory/swriter"
xWriterComponent = xComponentLoader~loadComponentFromURL(url, "_blank", 0, .UNO~noProps)
xText=xWriterComponent~XTextDocument~getText()

/* start at line 1 in Calc */
line = 0

/* do this until empty cell text is found */
do while xSheet~getCellByPosition(0,line)~getFormula() <> ""

	/* read all cell texts */
	surname = xSheet~getCellByPosition(0,line)~getFormula()
	familyname = xSheet~getCellByPosition(1,line)~getFormula()
	address = xSheet~getCellByPosition(2,line)~getFormula()
	zip = xSheet~getCellByPosition(3,line)~getFormula()
	city = xSheet~getCellByPosition(4,line)~getFormula()

	/* insert text in Writer */
	xText~getEnd~setString(surname %% " " %% familyname)
	call newline 1
	xText~getEnd~setString(address)
	call newline 1
	xText~getEnd~setString(zip %% " " %% city)
	call newline 5

	xText~getEnd~setString("Dear " %% surname %%"!")
	call newline 2
	/* insert the letter */
	xTextCursor = xText~getText~createTextCursor
	insertprops = bsf.createArray(.UNO~propertyValue, 0)
	xTextCursor~gotoEnd(.false)
	xTextCursor~XDocumentInsertable~insertDocumentFromURL("file:///C:/letter.odt", insertprops)

	/* perform a pagebreak */
	xCursorProps=xTextCursor~XPropertySet
	xCursorProps~setPropertyValue("BreakType", bsf.getConstant("com.sun.star.style.BreakType", "PAGE_AFTER"))
	call newline 1

line= line + 1
end

EXIT 0

/* function for inserting more than one carriage returns */
newline:
use arg count
do count
	xText~getEnd~setString("13" ~d2c)
end
return

::requires UNO.CLS

Changelog

DateUserModification
2006-07-10matthiaspremInitial version

and