OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Calc Examples
Goto page Previous  1, 2, 3, 4, 5, 6, 7  Next
 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Wed Jun 09, 2004 1:41 pm    Post subject: Reply with quote

Here is a program
http://www.oooforum.org/forum/viewtopic.php?p=36035#36035

...that does the following....
1. Creates a new spreadsheet
2. Puts some glowing sales figures into it (see the chart!)
3. Creates a chart of those sales figures
4. Creates a new drawing document.
5. Select/Copy/Paste the chart into the Drawing
6. Export the drawing to a JPEG.

A Java version of the program is then added to the thread linked above.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Sat Jun 26, 2004 10:33 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Jun 10, 2004 6:38 am    Post subject: Reply with quote

Column Number to Column Name and vice versa
http://www.oooforum.org/forum/viewtopic.php?p=23013#23013

and see also...
http://www.oooforum.org/forum/viewtopic.php?t=5597
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Sat Jun 26, 2004 10:32 am    Post subject: Reply with quote

Andrew Pitonyak's example of how to clear a cell range....
http://www.oooforum.org/forum/viewtopic.php?p=38164#38164

dfrench's example of finding Annotations (i.e. "show note") for a particular spreadsheet cell....
http://www.oooforum.org/forum/viewtopic.php?p=38160#38160
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Wed Jul 14, 2004 6:47 am    Post subject: Reply with quote

I just started a companion thread to this thread....

Draw Examples
http://www.oooforum.org/forum/viewtopic.php?t=10795
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
Mauro
Newbie
Newbie


Joined: 13 Sep 2004
Posts: 3

PostPosted: Mon Sep 13, 2004 9:32 am    Post subject: MS VB Skeleton Reply with quote

Very Happy Hi,
here is a skeleton of Mictosoft VB6 to control Oo
Must be created a prject with a command control called command1(default)
and insert following VB6SP5 code at Click Event
Code:

Private Sub Command1_Click()
Dim args()
Set oServiceManager = CreateObject("com.sun.star.ServiceManager")
'Create the Desktop
Set oDesktop = oServiceManager.createInstance("com.sun.star.frame.Desktop")
'Open a calc document
Set oDoc = oDesktop.loadComponentFromURL("file:///c:/prova.sxc", "_blank", 0, args)
Set oSheet = oDoc.getSheets().getByIndex(0)
'polls 3 cells
Set oCell = oSheet.getCellByPosition(0, 0)
Debug.Print oCell.Value
Set oCell = oSheet.getCellByPosition(0, 1)
Debug.Print oCell.Value
Set oCell = oSheet.getCellByPosition(1, 0)
Debug.Print oCell.Value
'write into a cell
Set oCell = oSheet.getCellByPosition(1, 1)
oCell.setvalue 44
'save the document
oDoc.storeToURL "file:///c:/prova2.sxc", args
'close Oo
oDoc.Close 1
End Sub

May be usefull will implement this code upon my job tasks?
_________________
Mauro
(This World is too wide for me)
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Sep 17, 2004 5:47 am    Post subject: Reply with quote

Example of how to display the names of the sheets in a Calc spreadsheet in a MsgBox using the Join function.
http://www.oooforum.org/forum/viewtopic.php?p=48276#48276

Example of how to display the names of the style famiilies and then the individual styles within a family using a MsgBox and the Join function.
http://www.oooforum.org/forum/viewtopic.php?p=48278#48278
This example uses a Writer document, but it actually works for any document type, including Calc.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Wed Sep 22, 2004 7:00 am    Post subject: Reply with quote

Example of how to create a Named Range in a spreadsheet. Similar to using Insert --> Names --> Define....

Code:
Sub Main
   oDoc = ThisComponent
   oDoc.NamedRanges.addNewByName( "John", "B2:C8", _
         createUnoStruct( "com.sun.star.table.CellAddress" ),_
         0 )
End Sub


The above example creates a named range with the name "John", that refers to cells B2:C8.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Wed Sep 22, 2004 1:28 pm    Post subject: Reply with quote

Here is an example that tells you what is selected in a spreadsheet.

If a cell is selected, it tells you the sheet and cell range.

If a drawing shape is selected, it tells you that.

If something else is selected, it tells you that.

Code:

Sub Main
   ' Get document model
   oDoc = ThisComponent
   ' Get the controller from the model.
   oDocCtrl = oDoc.getCurrentController()
   ' Get the frame from the controller.
'   oDocFrame = oDocCtrl.getFrame()
   
'   oSheet = oDoc.getSheets().getByIndex( 0 ) ' get first sheet by index
'   oSheet = oDoc.getSheets().getByName( "Sheet3" ) ' get by name
'   oSheet = oDocCtrl.getActiveSheet() ' ask controller for active sheet
   
   ' Ask the document controller for the selection.
   oSelection = oDocCtrl.getSelection()
   
   ' See if the selection is a range of cells.
   '  (As opposed to, say, a chart, or graphic, or text characters, etc....)
   If HasUnoInterfaces( oSelection, "com.sun.star.sheet.XCellRangeAddressable" ) Then
      ' Since the XCellRangeAddressable interface is supported, we can call getRangeAddress().
      oCellAddress = oSelection.getRangeAddress()
      ' The oCellAddress has a Sheet, StartColumn, EndColumn, StartRow, and EndRow.
      ' Get the sheet based on the sheet number from the selection.
      oTheSheet = oDoc.getSheets().getByIndex( oCellAddress.Sheet )
      ' Get the column names.
      cStartColumnName = CalcColumnNumberToName( oTheSheet, oCellAddress.StartColumn )
      cEndColumnName = CalcColumnNumberToName( oTheSheet, oCellAddress.EndColumn )
      ' Get the rows.
      cStartRow = CSTR( oCellAddress.StartRow )
      cEndRow = CSTR( oCellAddress.EndRow )
      ' Display the selection name.
      MsgBox oTheSheet.getName() + "!" + cStartColumnName + cStartRow + ":" + cEndColumnName + cEndRow

   ' See if the selection is a group of shapes....
   ElseIf HasUnoInterfaces( oSelection, "com.sun.star.drawing.XShapes" ) Then
      If oSelection.getCount() = 1 Then
         MsgBox "One drawing shape is selected.  Can't tell you a cell address."
      Else
         MsgBox "Several drawing shapes are selected.  Can't tell you a cell address."
      EndIf
   Else
      MsgBox "The selection is not a shape or a cell."
   EndIf
End Sub



Function CalcColumnNameToNumber( oSheet As com.sun.star.sheet.Spreadsheet,_
                     cColumnName As String ) As Long
   oColumns = oSheet.getColumns()
   oColumn = oColumns.getByName( cColumnName )
   oRangeAddress = oColumn.getRangeAddress()
   nColumn = oRangeAddress.StartColumn
   CalcColumnNameToNumber() = nColumn
End Function


Function CalcColumnNumberToName( oSheet As com.sun.star.sheet.Spreadsheet,_
                     nColumnNumber As Long ) As String
   oColumns = oSheet.getColumns()
   oColumn = oColumns.getByIndex( nColumnNumber )
   cColumnName = oColumn.getName()
   CalcColumnNumberToName() = cColumnName
End Function



2005-05-02....
Here is an interesting related thread....
How to get current focused cell?
http://www.oooforum.org/forum/viewtopic.phtml?t=19348
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Mon May 02, 2005 9:28 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Sep 23, 2004 11:59 am    Post subject: Reply with quote

Here are some examples of how to find the cells that are currently selected in a spreadsheet and process them in some way.

Two examples.


Example 0

This first example is the most simple.
First find out what is selected in the spreadsheet (if it actually even is a spreadsheet?).
If what is selected is not a range of cells, then complain about it.
If it is a range of cells, then iterate over each cell in the selected range, and print it into an annoying little dialog box using Basic's Print statement.

Code:
Sub Main
   ' Get document model of this document.
   '  (i.e. the document that contains this macro.)
   oDoc = ThisComponent
   ' Get the document model of the frontmost window.
   'oDoc = StarDesktop.getCurrentComponent()
   
   ' Get the selected cells, if any cells are selected.
   ' If this returns something,
   '  then it is a com.sun.star.sheet.SheetCellRange.
   oSheetCellRange = GetSelectedCellRange( oDoc )
   
   ' Were any cells returned?
   If IsEmpty( oSheetCellRange ) Or IsNull( oSheetCellRange ) Then
      MsgBox "A range of cells is not selected.  Please select one or more cells in the spreadsheet."
      Exit Sub
   EndIf

   ' Since the com.sun.star.sheet.XCellRangeAddressable interface is supported,
   '  we can call getRangeAddress().
   ' The getRangeAddress() returns a com.sun.star.table.CellRangeAddress,
   '  which has a Sheet, StartColumn, EndColumn, StartRow, and EndRow.
   oSelectedCellRangeAddress = oSheetCellRange.getRangeAddress()
   ' Since the com.sun.star.sheet.XSheetCellRange interface is supported,
   '  we can call getSpreadsheet().
   ' This gets us the particular sheet model that contains the selected cells.
   oSheet = oSheetCellRange.getSpreadsheet()
   
   ' Loop over all of the selected cells.
   For nRow = oSelectedCellRangeAddress.StartRow To oSelectedCellRangeAddress.EndRow
      For nCol = oSelectedCellRangeAddress.StartColumn To oSelectedCellRangeAddress.EndColumn
         ' Get the cell.
         oCell = oSheet.getCellByPosition( nCol, nRow )
         
         ' Print it's contents as a string.
         Print oCell.getString()
      Next
   Next
End Sub


' Return either Null, or a com.sun.star.sheet.SheetCellRange.
Function GetSelectedCellRange( oDoc )

   ' Is it a spreadsheet?
   If Not HasUnoInterfaces( oDoc, "com.sun.star.sheet.XSpreadsheetDocument" ) Then
      ' Not a spreadsheet.
      Exit Function
   EndIf
   
   ' At this point, oDoc is the *model* of a spreadsheet.
   
   ' Get the document's current controller.
   ' i.e. if the document has one or more windows open (multiple windows could be
   '  open by picking Window --> New Window), then return the current window
   '  controller for the document model.
   oDocCtrl = oDoc.getCurrentController()
   
   ' Now get the current selection from the controller.
   ' Ask the document controller for the selection.
   oSelection = oDocCtrl.getSelection()
   
   ' See if the selection is a range of cells.
   '  (As opposed to, say, a chart, or graphic, or text characters, etc....)
   If Not HasUnoInterfaces( oSelection, "com.sun.star.sheet.XCellRangeAddressable" ) Then
      ' Since the current selection is NOT a range of cells, bail out.
      Exit Function
   EndIf
   If Not HasUnoInterfaces( oSelection, "com.sun.star.sheet.XSheetCellRange" ) Then
      ' Since the current selection is NOT a range of cells, bail out.
      Exit Function
   EndIf
   
   ' Return it.
   GetSelectedCellRange = oSelection
End Function





Example 1

This example is a minor modification of the above example. Only the Main subroutine is changed.

In this next example, the contents of the spreadsheet cells are written into a new Writer (word processing) document.

You still need the GetSelectedCellRange() function from the above example.

In addition, two utility subroutines are necessary in order to "print" into a Writer document.

Code:
Sub Main
   ' Get document model of this document.
   '  (i.e. the document that contains this macro.)
   oDoc = ThisComponent
   ' Get the document model of the frontmost window.
   'oDoc = StarDesktop.getCurrentComponent()
   
   ' Get the selected cells, if any cells are selected.
   ' If this returns something,
   '  then it is a com.sun.star.sheet.SheetCellRange.
   oSheetCellRange = GetSelectedCellRange( oDoc )

   ' Were any cells returned?
   If IsEmpty( oSheetCellRange ) Or IsNull( oSheetCellRange ) Then
      MsgBox "A range of cells is not selected.  Please select one or more cells in the spreadsheet."
      Exit Sub
   EndIf
   
   '----------
   ' Prepare for output to Writer.
   ' Create a new Writer document.  Get its text, then create a new cursor on the text.
   oWriterDoc = StarDesktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, Array() )
   oWriterText = oWriterDoc.getText()
   oWriterCursor = oWriterText.createTextCursor()
   '----------

   ' Since the com.sun.star.sheet.XCellRangeAddressable interface is supported,
   '  we can call getRangeAddress().
   ' The getRangeAddress() returns a com.sun.star.table.CellRangeAddress,
   '  which has a Sheet, StartColumn, EndColumn, StartRow, and EndRow.
   oSelectedCellRangeAddress = oSheetCellRange.getRangeAddress()
   ' Since the com.sun.star.sheet.XSheetCellRange interface is supported,
   '  we can call getSpreadsheet().
   ' This gets us the particular sheet model that contains the selected cells.
   oSheet = oSheetCellRange.getSpreadsheet()
   
   ' Loop over all of the selected cells.
   For nRow = oSelectedCellRangeAddress.StartRow To oSelectedCellRangeAddress.EndRow
      For nCol = oSelectedCellRangeAddress.StartColumn To oSelectedCellRangeAddress.EndColumn
         ' Get the cell.
         oCell = oSheet.getCellByPosition( nCol, nRow )
         
         If nCol > oSelectedCellRangeAddress.StartColumn Then
            ' Insert a TAB character.
            Writer_Print( oWriterCursor, Chr(9) )
         EndIf
         ' Print it's contents as a string.
         Writer_Print( oWriterCursor, oCell.getString() )
      Next
      Writer_PrintLn( oWriterCursor )
   Next
End Sub



' Sugar Coated way to Print into a Writer document.
' The oOutput parameter can be any of....
'   com.sun.star.text.TextDocument
'   com.sun.star.drawing.Text
'   com.sun.star.text.TextCursor
Sub Writer_Print( oOutput, cString )
   If oOutput.SupportsService( "com.sun.star.text.TextDocument" ) Then
      oText = oOutput.getText()
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.drawing.Text" ) Then
      oText = oOutput
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.text.Text" ) Then
      oText = oOutput
      oCursor = oText.createTextCursor()
   ElseIf oOutput.SupportsService( "com.sun.star.text.TextCursor" ) Then
      oCursor = oOutput
      oText = oCursor.getText()
   Else
      Exit Sub
   EndIf
   
   oCursor.gotoEnd( False )
   
   nLen = Len( cString )
   nStart = 1
   Do
      nPos = Instr( nStart, cString, Chr(13) )
      bCRFound = (nPos > 0)
      If Not bCRFound Then
         nPos = nLen + 1
      EndIf
      cSegment = Mid( cString, nStart, nPos-nStart )
      nStart = nPos + 1
      
      oText.insertString( oCursor, cSegment, False )
      
      If bCRFound Then
         oText.insertControlCharacter( oCursor, com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False )
      EndIf
   Loop While bCRFound
End Sub

' Same as Writer_Print(), just adds a line ending.
Sub Writer_PrintLn( oOutput, Optional cString )
   If IsMissing( cString ) Then
      cString = ""
   EndIf
   Writer_Print( oOutput, cString + Chr(13) )
End Sub




Example 2

This example is a minor modification of the above two examples. Only the Main subroutine is changed.

In this example, the contents of the spreadsheet cells are written into a text file on disk. (Be sure to change the output pathname!)

You still need the GetSelectedCellRange() function from the above example.

In addition, some utility functions are needed in order to assist with the low level I/O to a text file.

Code:
Sub Main
   ' Get document model of this document.
   '  (i.e. the document that contains this macro.)
   oDoc = ThisComponent
   ' Get the document model of the frontmost window.
   'oDoc = StarDesktop.getCurrentComponent()
   
   ' Get the selected cells, if any cells are selected.
   ' If this returns something,
   '  then it is a com.sun.star.sheet.SheetCellRange.
   oSheetCellRange = GetSelectedCellRange( oDoc )

   ' Were any cells returned?
   If IsEmpty( oSheetCellRange ) Or IsNull( oSheetCellRange ) Then
      MsgBox "A range of cells is not selected.  Please select one or more cells in the spreadsheet."
      Exit Sub
   EndIf
   
   '----------
   ' Prepare for output to text file.
   cOutputFilePathname = "C:\Documents and Settings\dbrewer\Desktop\output.txt"
   cOutputURL = ConvertToURL( cOutputFilePathname )
   ' Create a SimpleFileAccess service.
   oSimpleFileAccess = createUnoService( "com.sun.star.ucb.SimpleFileAccess" )
   ' Ask it output file already exists?
   If oSimpleFileAccess.exists( cOutputURL ) Then
      ' Delete the file.
      oSimpleFileAccess.kill( cOutputURL )
   EndIf
   ' Create the output file.
   oOutputFile = oSimpleFileAccess.openFileWrite( cOutputURL )
   '----------

   ' Since the com.sun.star.sheet.XCellRangeAddressable interface is supported,
   '  we can call getRangeAddress().
   ' The getRangeAddress() returns a com.sun.star.table.CellRangeAddress,
   '  which has a Sheet, StartColumn, EndColumn, StartRow, and EndRow.
   oSelectedCellRangeAddress = oSheetCellRange.getRangeAddress()
   ' Since the com.sun.star.sheet.XSheetCellRange interface is supported,
   '  we can call getSpreadsheet().
   ' This gets us the particular sheet model that contains the selected cells.
   oSheet = oSheetCellRange.getSpreadsheet()
   
   ' Loop over all of the selected cells.
   For nRow = oSelectedCellRangeAddress.StartRow To oSelectedCellRangeAddress.EndRow
      For nCol = oSelectedCellRangeAddress.StartColumn To oSelectedCellRangeAddress.EndColumn
         ' Get the cell.
         oCell = oSheet.getCellByPosition( nCol, nRow )
         
         If nCol > oSelectedCellRangeAddress.StartColumn Then
            ' Output a TAB character.
            oOutputFile.writeBytes( StringToByteArray( Chr(9) ) )
         EndIf
         ' Output it's contents as a string.
         oOutputFile.writeBytes( StringToByteArray( oCell.getString() ) )
      Next
      ' Output out a CR-LF
      oOutputFile.writeBytes( StringToByteArray( Chr(13)+Chr(10) ) )
   Next
   
   ' Close output file.
   oOutputFile.closeOutput()
End Sub




'############################################################
'   Convenience routines for working with
'      com.sun.star.io.XInputStream
'      com.sun.star.io.XOutputStream
'############################################################



' Convert an array of bytes to a string.
' Pass in an array of bytes.
' Each "byte" in the array is an integer value from -128 to +127.
' The array of bytes could have come from reading
'  from a com.sun.star.io.XInputStream.
' This function returns a string.
' This function is the opposite of StringToByteArray().
Function ByteArrayToString( aByteArray )
   cBytes = ""
   For i = LBound( aByteArray ) To UBound( aByteArray )
      nByte = aByteArray(i)
      nByte = ByteToInteger( nByte )
      cBytes = cBytes + Chr( nByte )
   Next i
   ByteArrayToString() = cBytes
End Function


' Convert a string into an array of bytes.
' Pass a string value to the cString parameter.
' The function returns an array of bytes, suitable
'  for writing to a com.sun.star.io.XOutputStream.
' Each "byte" in the array is an integer value from -128 to +127.
' This function is the opposite of ByteArrayToString().
Function StringToByteArray( ByVal cString As String )
   nNumBytes = Len( cString )
   Dim aBytes(nNumBytes-1) As Integer
   For i = 1 To nNumBytes
      cChar = Mid( cString, i, 1 )
      nByte = Asc( cChar )
      nByte = IntegerToByte( nByte )
      aBytes(i-1) = nByte
   Next
   StringToByteArray() = aBytes()
End Function





'############################################################
'   Signed and Unsigned Byte conversion.
'############################################################


' Convert a byte value from the range -128 to +127 into
'  an integer in the range 0 to 255.
' This function is the opposite of IntegerToByte().
Function ByteToInteger( ByVal nByte As Integer ) As Integer
   If nByte < 0 Then
      nByte = nByte + 256
   EndIf
   ByteToInteger() = nByte
End Function


' This function is the opposite of ByteToInteger().
Function IntegerToByte( ByVal nByte As Integer ) As Integer
   If nByte > 127 Then
      nByte = nByte - 256
   EndIf
   IntegerToByte() = nByte
End Function


I hope these two examples are helpful.

Be sure to see the next message in this thread.



2005-05-02....
Here is an interesting related thread....
How to get current focused cell?
http://www.oooforum.org/forum/viewtopic.phtml?t=19348
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Mon May 02, 2005 9:28 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Sep 24, 2004 5:53 am    Post subject: Reply with quote

I slightly edited the examples of the immediately preceeding message. Only comments were affected.

Here is a little bit more elaboration.

See these lines in the above examples.
Code:
   ' Since the com.sun.star.sheet.XCellRangeAddressable interface is supported,
   '  we can call getRangeAddress().
   ' The getRangeAddress() returns a com.sun.star.table.CellRangeAddress,
   '  which has a Sheet, StartColumn, EndColumn, StartRow, and EndRow.
   oSelectedCellRangeAddress = oSheetCellRange.getRangeAddress()
   ' Since the com.sun.star.sheet.XSheetCellRange interface is supported,
   '  we can call getSpreadsheet().
   ' This gets us the particular sheet model that contains the selected cells.
   oSheet = oSheetCellRange.getSpreadsheet()


The oSelectedCellRangeAddress variable has a struct (a com.sun.star.table.CellRangeAddress) which has a Sheet member, which is a number, the index of the spreadsheet holding the selected cell range. It also has StartRow, StartColumn, EndRow and EndColumn; which I demonstrated how to use.

You could use the Sheet member to get the sheet from the document like this....
oSheet = oDoc.getSheets().getByIndex( oSelectedCellRangeAddress.Sheet )
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Tue Sep 28, 2004 9:08 am    Post subject: Reply with quote

This is the answer to this question.
http://www.oooforum.org/forum/viewtopic.php?t=12809
bitpicker wrote:
I'd like to have a button or something similar next to it, and when I click it the value of the price should be added to a sum total in another cell in the same line

The original thread now contains a bit more detail on how to adapt this example to the specific solution. Specifically, moving the focus when the button is clicked.

The following is an example of how to create a button that is copied and pasted onto many rows. All of the buttons call the same macro. The macro function is then able to manipulate cells in columns of THAT ROW on which the button is located.

Here are the destructions.

Create a spreadsheet.
Paste the following code into its macros. (Apologies in advance, warning, contains more lines of comments than lines of actual code.)
Code:
' This routine is called by multiple buttons on the spreadsheet.
' The buttons are in the same column, but different rows.
' This routine does something to the cells on a single row,
'  that is, the row, that the button lives on.
Sub ButtonClick( oEvent )
   ' Get the control which called this routine.
   oButtonCtrl = oEvent.Source
   ' Get the control's model from the control.
   oButtonModel = oButtonCtrl.getModel()
   
   ' Get the name of the button.
   'cButtonName = oButtonModel.Name
   
   ' Get this document model.
   oDoc = ThisComponent
   ' Get the current controller.
   '  (i.e. the controller associated with whichever window is currently viewing the sheet.)
   ' Note, multiple windows can view the sheet by picking, Window --> New Window.
   oDocCtrl =  oDoc.getCurrentController()
   ' Get the active sheet in the window.
   oSheet = oDocCtrl.getActiveSheet()
   
   ' Go on a wild goose chase for the control shape.
   ' We'll assume that buttons calling this routine are on the Standard form.
   oControlShape = FindControlShape( oSheet, "Standard", oButtonModel )
   
   ' Finally, get the spreadsheet cell that the button is anchored to.
   oCell = oControlShape.getAnchor()
   ' Get the Row of the cell.  This is what we've been wanting the whole time.
   nRow = oCell.getRangeAddress().StartRow
   
   
   ' Now that we finally know the row of the button that called us,
   '  Let's increment the value in column B of the same row.
   nCurValue = oSheet.getCellByPosition( 1, nRow ).getValue()
   oSheet.getCellByPosition( 1, nRow ).setValue( nCurValue + 1 )
End Sub


' Given the control model on a sheet, search for the control's shape.
Function FindControlShape( oSheet, cFormName, oWantedControlModel )
   oDrawPage = oSheet.getDrawPage()
   oForms = oDrawPage.getForms()
   oForm = oForms.getByName( cFormName )
   
   nNumShapes = oDrawPage.getCount()
   For i = 0 To nNumShapes - 1
      oShape = oDrawPage.getByIndex( i )
      If HasUnoInterfaces( oShape, "com.sun.star.drawing.XControlShape" ) Then
         oControlModel = oShape.getControl()
         If EqualUnoObjects( oWantedControlModel, oControlModel ) Then
            FindControlShape = oShape
            Exit Function
         EndIf
      EndIf
   Next
End Function


Now on the spreadsheet, draw a single button. Do NOT draw it in column B of the spreadsheet (because that is what the Macro modifies). Draw the button completely within a single cell -- the button should not stretch out of the row..

Alter the properties of the button, particularly, the button's Label.
Be SURE to alter the button's When Initiating event to call the ButtonClick subroutine above.

Now select a cell. Use the tab and/or arrow keys to move the focus to the cell containing the button. Copy. You have copied the button. Note that what you did was select the cell not select the button.

Now move the focus to the cell on the row below. Paste.
Now you can do a DownArrow, Paste, DownArrow, Paste, etc. In fact, you can select a vertical column of cells and then Paste once to paste a copy of the button into many rows, in the same column.

All of the buttons point at the same macro routine. When you click a button, it adds one to the count in column B of the same row.

Thanks to B Marcelly
http://www.oooforum.org/forum/viewtopic.php?p=49008#49008
for recently pointing out that the event subroutine is passed an event. From the event.source it was "simply" a matter of following a very complicated maze of objects, eventually ending in doing a search for the control shape, to get to the row that the button is on.
http://www.oooforum.org/forum/viewtopic.php?p=49437#49437


See this related example later in this thread....
http://www.oooforum.org/forum/viewtopic.php?p=53737#53737
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Tue Nov 02, 2004 7:46 am; edited 1 time in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Sat Oct 02, 2004 2:24 pm    Post subject: Reply with quote

The following is an example of how to program Calc in Java.
This is mostly a duplication of the first message in this thread, which is written in Basic.

In order to make the following code work, you will need some classes from this thread....

Danny's Java classes
http://www.oooforum.org/forum/viewtopic.php?t=12954

The names of the classes you need...
name.DannyBrewer.OOoUno.OOoUtils
name.DannyBrewer.OOoUno.QI
name.DannyBrewer.OOoUno.OOoCalcUtils

You need the latest versions of the above classes.

Here is the Calc Examples in Java. (I have added the Chart example from the Basic example at the first of this thread.)

Please note that where I write
XSomething y = QI.XSomething( z )
that this is simply a sugar coating for the uglier and longer....
XSomething y = (XSomething) UnoRuntime.queryInterface( XSomething.class, z )
The reason for the sugar coating is because queryInterface is done so frequently.

Code:
/*
 * CalcExamples.java
 *
 * Created on September 28, 2004, 10:27 AM
 *
 * Author: Danny Brewer
 *
 * Copyright 2004 Danny Brewer
 * Anyone may run this code.
 * If you wish to modify or distribute this code, then
 *  you are granted a license to do so only under the terms
 *  of the Gnu Lesser General Public License.
 * See:  http://www.gnu.org/licenses/lgpl.html
 */

package ExamplePrograms;

import name.DannyBrewer.OOoUno.QI;
import name.DannyBrewer.OOoUno.OOoUtils;
import name.DannyBrewer.OOoUno.OOoCalcUtils;


//----------------------------------------------------------------------
//  OpenOffice.org imports
//----------------------------------------------------------------------

//import com.sun.star.awt.*;
import com.sun.star.beans.*;
import com.sun.star.chart.*;
import com.sun.star.container.*;
import com.sun.star.document.*;
import com.sun.star.drawing.*;
import com.sun.star.frame.*;
import com.sun.star.lang.*;
import com.sun.star.sheet.*;
import com.sun.star.style.*;
import com.sun.star.table.*;
//import com.sun.star.text.*;
//import com.sun.star.uno.*;
import com.sun.star.util.*;
import com.sun.star.view.*;


/**
 *
 * @author  Danny Brewer
 */
public class CalcExamples {
   

    /** Creates a new instance of CalcExamples */
    public CalcExamples() {
    }
   
    public static void main( String[] args ) {
        try {
            // Get the service manager
            XMultiServiceFactory serviceManager = OOoUtils.getRemoteOOoServiceManager();
            // alternate version...
            //XMultiServiceFactory serviceManager = OOoUtils.getRemoteOOoServiceManager( "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" );
           
            // Get the desktop from the service manager.
            XComponentLoader desktop = OOoUtils.getDesktop( serviceManager );

            // Use this url to create a new Calc document.
            String url = "private:factory/scalc";
            // Use this URL to open an existing Calc document.
            //String url = "file:///home/danny/Desktop/Something.sxc";
            // Use this URL on systems infected with Windows.
            //String url = "file:///C:/Documents and Settings/dbrewer/Desktop/Something.sxc";
           
            // Ask the Desktop's component loader to load the url for a new Draw document.
            // This might throw com.sun.star.uno.Exception.
            // This gives us a document model.
            // It gives us the XComponent interface to the document.
            // There are other interfaces to this object available via. queryInterface.
            XComponent calcDoc_XComponent = desktop.loadComponentFromURL( url, "_blank", 0, new PropertyValue [0] );
           
            //-----
            // Get some of the other interfaces to the document that we will need.
            // We do this by calling UnoRuntime.queryInterface().
            // The QI.XXX() functions are just a sugar coated wraper.
            XSpreadsheetDocument    calcDoc_XSpreadsheetDocument    = QI.XSpreadsheetDocument( calcDoc_XComponent );
            XNumberFormatsSupplier  calcDoc_XNumberFormatsSupplier  = QI.XNumberFormatsSupplier( calcDoc_XComponent );
            XModel                  calcDoc_XModel                  = QI.XModel( calcDoc_XSpreadsheetDocument );
            XPrintable              calcDoc_XPrintable              = QI.XPrintable( calcDoc_XSpreadsheetDocument );
            // At this point, the variables
            //   calcDoc_XComponent
            //   calcDoc_XSpreadsheetDocument
            //   calcDoc_XNumberFormatsSupplier
            //   calcDoc_XModel
            //   calcDoc_XPrintable
            //  point to the same service.  Just different interfaces of it.
            // It is important to understand that all of these variables point to the SAME service.
            //-----
           
            //-----
            //  Later in the program we will need the document controller and frame.
            //
            // First get one of the document's controllers.
            // The document may have more than one controller.
            // How?  When you have an OOo document open, try picking Window --> New Window.
            // Each controller has one frame, each frame has one controller. (1:1 relationship)
            // Each controller has one document model.  The document model may have multiple controllers.  (many:1 relationship)
            //
            // Get the current controller from the document model.
            XController calcDocController = calcDoc_XModel.getCurrentController();
            // Get the frame from the controller.
            XFrame calcDocFrame = calcDocController.getFrame();
            //-----
           
            // Get the collection of spreadsheets from the document.
            // This collection can be accessed by number (XIndexAccess) or by name (XNameAccess).
            XSpreadsheets sheets_XSpreadsheets = calcDoc_XSpreadsheetDocument.getSheets();
            XIndexAccess sheets_XIndexAccess = QI.XIndexAccess( sheets_XSpreadsheets );
            // At this point, the variables
            //   sheets_XSpreadsheets
            //   sheets_XIndexAccess
            //  point to the same service.  Just different interfaces of it.
           
            // Here are two ways to get access to one of the various sheets
            //  in the spreadsheet document.
            // Note that these don't make the sheet *vislble*, they merely give
            //  access to the sheet's content within the program.
            Object sheet = sheets_XIndexAccess.getByIndex( 0 ); // By index
            //Object sheet = sheets_XSpreadsheets.getByName( "Sheet3" ); // By name
           
            XSpreadsheet sheet_XSpreadsheet = QI.XSpreadsheet( sheet );
            // At this point, the variables
            //   sheet
            //   sheet_XSpreadsheet
            //  point to the same service.  Just different interfaces of it.
           
            //----------
            //  Put some sales figures onto the sheet.
            //  Set some cells by cell col,row position; set other cells by cell name.
            //
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 0, "Month" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 1, 0, "Sales" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 2, 0, "End Date" );

            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 1, "Jan" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 2, "Feb" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 3, "Mar" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 4, "Apr" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 5, "May" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, 0, 6, "Jun" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A8", "Jul" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A9", "Aug" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A10", "Sep" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A11", "Oct" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A12", "Nov" );
            OOoCalcUtils.setCellString( sheet_XSpreadsheet, "A13", "Dec" );

            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 1, 3826.37 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 2, 3504.21 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 3, 2961.45 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 4, 2504.12 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 5, 2713.98 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, 1, 6, 2248.17 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B8", 1802.13 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B9", 2003.22 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B10", 1502.54 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B11", 1207.68 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B12", 1319.71 );
            OOoCalcUtils.setCellValue( sheet_XSpreadsheet, "B13", 786.03 );

            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 1, "=DATE(2004;01;31)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 2, "=DATE(2004;02;29)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 3, "=DATE(2004;03;31)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 4, "=DATE(2004;04;30)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 5, "=DATE(2004;05;31)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, 2, 6, "=DATE(2004;06;30)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C8", "=DATE(2004;07;31)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C9", "=DATE(2004;08;31)" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C10", "=DATE(2004;09;30)" );
            // Note that these last three dates are not set as DATE() function calls.
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C11", "10/31/2004" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C12", "11/30/2004" );
            OOoCalcUtils.setCellFormula( sheet_XSpreadsheet, "C13", "12/31/2004" );
            //
            //----------
           
            //----------
            //  Format the date cells as dates.
            //
           
            XNumberFormats numberFormats_XNumberFormats = calcDoc_XNumberFormatsSupplier.getNumberFormats();
            XNumberFormatTypes numberFormats_XNumberFormatTypes = QI.XNumberFormatTypes( numberFormats_XNumberFormats );
            // At this point, the variables
            //   numberFormats_XNumberFormats
            //   numberFormats_XNumberFormatTypes
            //  point to the same service.  Just different interfaces of it.
           
            Locale locale = new Locale();
            int nDateKey = numberFormats_XNumberFormatTypes.getStandardFormat( com.sun.star.util.NumberFormat.DATE, locale );
           
            XCellRange cellRange_XCellRange = sheet_XSpreadsheet.getCellRangeByName( "C2:C13" );
            OOoUtils.setIntProperty( cellRange_XCellRange, "NumberFormat", nDateKey );
            //
            //----------

            //----------
            //  Now add a chart to the spreadsheet.
            //
            cellRange_XCellRange = sheet_XSpreadsheet.getCellRangeByName( "A1:B13" );
            XCellRangeAddressable cellRange_XCellRangeAddressable = QI.XCellRangeAddressable( cellRange_XCellRange );
            // At this point, the variables
            //   cellRange_XCellRange
            //   cellRange_XCellRangeAddressable
            //  point to the same service.  Just different interfaces of it.
           
            CellRangeAddress cellRangeAddress = cellRange_XCellRangeAddressable.getRangeAddress();
           
            XTableChartsSupplier sheet_XTableChartsSupplier = QI.XTableChartsSupplier( sheet_XSpreadsheet );
            // At this point, the variables
            //   sheet_XSpreadsheet
            //   sheet_XTableChartsSupplier
            //  point to the same service.  Just different interfaces of it.
           
            // Get the collection of charts from the sheet.
            XTableCharts charts = sheet_XTableChartsSupplier.getCharts();
           
            // Add a new chart with a specific name,
            //  in a specific rectangle on the drawing page,
            //  and connected to specific cells of the spreadsheet.
            charts.addNewByName( "Sales",
                            OOoUtils.makeRectangle( 8000, 1000, 16000, 10000 ),
                            new CellRangeAddress[] { cellRangeAddress },
                            true, true );
           
            // From the collection of charts, get the new chart we just created.
            Object chart = charts.getByName( "Sales" );
            XTableChart chart_XTableChart = QI.XTableChart( chart );
            XEmbeddedObjectSupplier chart_XEmbeddedObjectSupplier = QI.XEmbeddedObjectSupplier( chart );
            // At this point, the variables
            //   chart
            //   chart_XTableChart
            //   chart_XEmbeddedObjectSupplier
            //  point to the same service.  Just different interfaces of it.
           
            // Get the chart document model.
            Object chartDoc = chart_XEmbeddedObjectSupplier.getEmbeddedObject();
            XChartDocument chartDoc_XChartDocument = QI.XChartDocument( chartDoc );
            XMultiServiceFactory chartDoc_XMultiServiceFactory = QI.XMultiServiceFactory( chartDoc );
            // At this point, the variables
            //   chartDoc
            //   chartDoc_XChartDocument
            //   chartDoc_XMultiServiceFactory
            //  point to the same service.  Just different interfaces of it.
           
            // Get the drawing text shape of the title of the chart.
            XShape titleTextShape = chartDoc_XChartDocument.getTitle();
            // Change the title.
            OOoUtils.setStringProperty( titleTextShape, "String", "Sales Chart" );
           
            // Create a diagram.
            Object diagram = chartDoc_XMultiServiceFactory.createInstance( "com.sun.star.chart.BarDiagram" );
            XDiagram diagram_XDiagram = QI.XDiagram( diagram );
            // At this point, the variables
            //   diagram
            //   diagram_XDiagram
            //  point to the same service.  Just different interfaces of it.
           
            // Set its parameters.
            OOoUtils.setBooleanProperty( diagram, "Vertical", true );
           
            // Make the chart use this diagram.
            chartDoc_XChartDocument.setDiagram( diagram_XDiagram );
           
            // Ask the chart what diagram it is using.
            // (Unnecessary, since variable oDiagram already contains this value -- see previous statement.)
            diagram_XDiagram = chartDoc_XChartDocument.getDiagram();
           
            // Make more changes to the diagram.
            OOoUtils.setIntProperty( diagram, "DataCaption", com.sun.star.chart.ChartDataCaption.VALUE );
            OOoUtils.setIntProperty( diagram, "DataRowSource", 1 /* com.sun.star.chart.ChartDataRowSource.COLUMNS */ );
            //
            //----------

            //----------
            //  Now demonstrate how to manipulate the sheets.
            //
            // Insert six more sheets into the document.
            int numSheetsCurrently = sheets_XIndexAccess.getCount();
            sheets_XSpreadsheets.insertNewByName( "Fred", (short)(numSheetsCurrently+1) );
            sheets_XSpreadsheets.insertNewByName( "Joe", (short)(numSheetsCurrently+2) );
            sheets_XSpreadsheets.insertNewByName( "Bill", (short)(numSheetsCurrently+3) );
            sheets_XSpreadsheets.insertNewByName( "Sam", (short)(numSheetsCurrently+4) );
            sheets_XSpreadsheets.insertNewByName( "Tom", (short)(numSheetsCurrently+5) );
            sheets_XSpreadsheets.insertNewByName( "David", (short)(numSheetsCurrently+6) );
            // Now find a sheet named "Sheet2" and get rid of it.
            sheets_XSpreadsheets.removeByName( "Sheet2" );
            // Now find the sheet named "Sam" and change its name to "Sheet 37"
            OOoUtils.XNamed_setName( sheets_XSpreadsheets.getByName( "Sam" ), "Sheet 37" );
            //
            //----------
           
            //----------
            //  Examples of getting or setting the selection.
           
            // From the controller, get a different interface of the controller.
            XSelectionSupplier calcDocController_XSelectionSupplier = QI.XSelectionSupplier( calcDocController );
            // At this point, the variables
            //   calcDocController
            //   calcDocController_XSelectionSupplier
            //  point to the same service.  Just different interfaces of it.
           
            //  Select some cells in the spreadsheet.
           
            // Select a certian cell by position.
            XCell oneCell = sheet_XSpreadsheet.getCellByPosition( 0, 4 );  // Cell A5
            calcDocController_XSelectionSupplier.select( oneCell );
           
            // Select some cells by position.
            XCellRange oneOrMoreCells = sheet_XSpreadsheet.getCellRangeByPosition( 0, 4, 1, 6 ); // Cells A5:B7
            calcDocController_XSelectionSupplier.select( oneOrMoreCells );
           
            // Select a single cell by name.
            oneOrMoreCells = sheet_XSpreadsheet.getCellRangeByName( "A8" );  // a group of one cell
            oneCell = oneOrMoreCells.getCellByPosition( 0, 0 ); // get the top left cell of the group
            calcDocController_XSelectionSupplier.select( oneCell );
//            calcDocController_XSelectionSupplier.select( oneOrMoreCells ); // we could have done this instead
           
            // Select a range of cells by name.
            oneOrMoreCells = sheet_XSpreadsheet.getCellRangeByName( "A8:C13" );
            calcDocController_XSelectionSupplier.select( oneOrMoreCells );

            // Let's find out what is selected.
            Object selection = calcDocController_XSelectionSupplier.getSelection();
            if( selection == null ) {
                System.out.println( "Nothing is selected." );
            } else if( QI.XCellRangeAddressable( selection ) != null ) {
                CellRangeAddress cellsAddress = QI.XCellRangeAddressable( selection ).getRangeAddress();
                System.out.println( "A range of cells are selected.  sheet=" + cellsAddress.Sheet
                                   + ", col1=" + cellsAddress.StartColumn + ", row1=" + cellsAddress.StartRow
                                        + ", col2=" + cellsAddress.EndColumn   + ", row2=" + cellsAddress.EndRow );
            } else if( QI.XShapes( selection ) != null ) {
                System.out.println( "One or more drawing shapes selected." );
            } else {
                System.out.println( "Something unknown is selected." );
            }
            //----------
           
            //----------
            //  Now print the document -- three different ways.
            //
            // Change me to true to actually do the following...
            if( false ) {
                // Technique 1.
                // Now print the document.
                // Print two copies.
                // Print pages 1 thru 4, and also page 10.
                calcDoc_XPrintable.print(
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "CopyCount", 2 ),
                        OOoUtils.makePropertyValue( "Pages", "1-4;10" )
                    });
            }
            //
            // Change me to true to actually do the following...
            if( false ) {
                // Technique 2.
                // Print the document already, without any arguments.
                calcDoc_XPrintable.print( new PropertyValue[0] );
            }
           
            // Change me to true to actually do the following...
            if( false ) {
                // Technique 3.
                // Print the document by bringing up the Print Job dialog box
                //  for the user to interact with.
               
                XDispatchProvider calcDocFrame_XDispatchProvider = QI.XDispatchProvider( calcDocFrame );
                Object dispatchHelper = serviceManager.createInstance( "com.sun.star.frame.DispatchHelper" );
                XDispatchHelper dispatchHelper_XDispatchHelper = QI.XDispatchHelper( dispatchHelper );
                dispatchHelper_XDispatchHelper.executeDispatch( calcDocFrame_XDispatchProvider, ".uno:Print", "", 0, new PropertyValue[0] );
            }
            //
            //----------

            //----------
            //  Now save the document
            //
            XStorable calcDoc_XStorable = QI.XStorable( calcDoc_XSpreadsheetDocument );
            // At this point, the variables
            //   calcDoc_XComponent
            //   calcDoc_XSpreadsheetDocument
            //   calcDoc_XNumberFormatsSupplier
            //   calcDoc_XPrintable
            //   calcDoc_XModel
            //   calcDoc_XStorable
            //  point to the same service.  Just different interfaces of it.

            // Prepare the filename to save.
            String cFileUrl = "file:///C:/Documents and Settings/dbrewer/Desktop/MyCalc"; // Windows
            //String cFileUrl = "file:///home/danny/Desktop/MyCalc"; // Linux
           
            // Change me to true to actually do the following...
            if( false ) {
                // Now save the spreadsheet in native OOo Calc format.
                calcDoc_XStorable.storeAsURL( cFileUrl+".sxc", new PropertyValue[0] );

                // Note the above used storeAsUrl, the following use storeToUrl.

                // Now save it in Excel format.
                calcDoc_XStorable.storeToURL( cFileUrl+".xls",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "MS Excel 97" )
                    });

                // Now save a PDF.
                calcDoc_XStorable.storeToURL( cFileUrl+".pdf",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "calc_pdf_Export" )
                    });

                // Now save it in CSV format.
                calcDoc_XStorable.storeToURL( cFileUrl+".csv",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "Text - txt - csv (StarCalc)" )
                    });

                // Now save it in DIF format.
                calcDoc_XStorable.storeToURL( cFileUrl+".dif",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "DIF" )
                    });

                // Now save it in SYLK format
                calcDoc_XStorable.storeToURL( cFileUrl+".sylk",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "SYLK" )
                    });

                // Now save as HTML.
                calcDoc_XStorable.storeToURL( cFileUrl+".html",
                    new PropertyValue[] {
                        OOoUtils.makePropertyValue( "FilterName", "HTML (StarCalc)" )
                    });
            }
            // A list of some filter names you can use for both loading
            //  and saving a document can be found here...
            //    http://www.oooforum.org/forum/viewtopic.php?t=3549
            //
            //----------
           
            //----------
            //  Now close the document
            XCloseable calcDoc_XCloseable = QI.XCloseable( calcDoc_XSpreadsheetDocument );
            // At this point, the variables
            //   calcDoc_XComponent
            //   calcDoc_XSpreadsheetDocument
            //   calcDoc_XNumberFormatsSupplier
            //   calcDoc_XPrintable
            //   calcDoc_XModel
            //   calcDoc_XStorable
            //   calcDoc_XCloseable
            //  point to the same service.  Just different interfaces of it.

            // Change me to true to actually do the following...
            if( false ) {           
                calcDoc_XCloseable.close( true );
            }
            //----------
           
        } catch( Exception e ) {
            System.out.println( "Something really stupid happened." + e );
        }
    }
 
}

_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Sat Nov 20, 2004 11:05 am; edited 3 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Oct 07, 2004 5:30 am    Post subject: Reply with quote

Here are a few utility functions that can be helpful in working with Calc.

Originally posted here....
http://www.oooforum.org/forum/viewtopic.php?p=50596#50596

Code:
Sub SetCellString( oSheet, cCellName, cString )
   oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).setString( cString )
End Sub

Function GetCellString( oSheet, cCellName )
   GetCellString = oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).getString()
End Function

Sub SetCellValue( oSheet, cCellName, cValue )
   oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).setValue( cValue )
End Sub

Function GetCellValue( oSheet, cCellName )
   GetCellValue = oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).getValue()
End Function

Sub SetCellFormula( oSheet, cCellName, cFormula )
   oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).setFormula( cFormula )
End Sub

Function GetCellFormula( oSheet, cCellName )
   GetCellFormula = oSheet.getCellRangeByName( cCellName ).getCellByPosition( 0, 0 ).getFormula()
End Function


Here is an example
http://www.oooforum.org/forum/viewtopic.php?p=50874#50874
that shows how easy it is to use the above functions.
_________________
Want to make OOo Drawings like the colored flower design to the left?


Last edited by DannyB on Fri Oct 08, 2004 1:03 pm; edited 2 times in total
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Oct 08, 2004 7:04 am    Post subject: Reply with quote

Here is an example....
http://www.oooforum.org/forum/viewtopic.php?p=50864#50864
....of how to use the FunctionAccess and FunctionDescriptions services to both call a Calc function from Basic, and how to produce a Writer document showing all of the available Calc functions in Basic.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Fri Oct 08, 2004 1:07 pm    Post subject: Reply with quote

I have updated the Java example above at.
http://www.oooforum.org/forum/viewtopic.php?p=50063#50063

It now has the Chart example.

Some of the cells are filled in by their position (getCellByPosition) and some are filled in by the cell name, which makes for a more complete example.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Goto page Previous  1, 2, 3, 4, 5, 6, 7  Next
Page 3 of 7

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group