<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>getDataArray &#8211; tutolibro.org</title>
	<atom:link href="https://tutolibro.org/tag/getdataarray/feed/" rel="self" type="application/rss+xml" />
	<link>https://tutolibro.org</link>
	<description>Free online tutorials</description>
	<lastBuildDate>Tue, 21 Jan 2025 11:12:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://tutolibro.org/wp-content/uploads/2020/02/cropped-logo_mini-32x32.png</url>
	<title>getDataArray &#8211; tutolibro.org</title>
	<link>https://tutolibro.org</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">173775150</site>	<item>
		<title>LibreOffice Calc &#038; Python Programming: part 7 – From Cells Range to Python Tuple.</title>
		<link>https://tutolibro.org/2020/07/10/libreoffice-calc-python-programming-part-7-from-cells-range-to-python-tuple/</link>
					<comments>https://tutolibro.org/2020/07/10/libreoffice-calc-python-programming-part-7-from-cells-range-to-python-tuple/#comments</comments>
		
		<dc:creator><![CDATA[gweno]]></dc:creator>
		<pubDate>Fri, 10 Jul 2020 23:54:50 +0000</pubDate>
				<category><![CDATA[Calc]]></category>
		<category><![CDATA[LibreOffice]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[calc]]></category>
		<category><![CDATA[cell type]]></category>
		<category><![CDATA[getDataArray]]></category>
		<category><![CDATA[libreoffice]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://tutolibro.tech/?p=998</guid>

					<description><![CDATA[The topic for this episode of my LibreOffice Calc &#38; Python Programming tutorial series is to get the data stored in a range of cells in LibreOffice. And we are going to do that using some very useful dedicated Pythons...<br /><a class="read-more-button" href="https://tutolibro.org/2020/07/10/libreoffice-calc-python-programming-part-7-from-cells-range-to-python-tuple/">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p>The topic for this episode of my LibreOffice Calc &amp; Python Programming tutorial series is to get the data stored in a range of cells in LibreOffice. And we are going to do that using some very useful dedicated Pythons Functions delivered with the PyUno library.</p>



<h4 class="wp-block-heading">How are we going to do it?</h4>



<p>We are going to get the coordinates of a range of selected cells in an open Calc document and store all the data that the range of cells contains into an Tuple.</p>



<p>But first, what is an <strong>Tuple</strong>?</p>



<p>A Tuple in Python is like an Array of data but that can store data with different types.<br>But what is an Array?<br>An array in computer programming is a container that stores data in consecutive memory addresses. It is widely used in many programming languages.<br>In Python an Array is used to store many variables with the same type of data (string, integer, float, etc&#8230;) which is not convenient for storing data coming from a Spreadsheet&#8217;s cells.<br>That is where the Tuple is convenient as it can store data of different types (see the 4 possible types in<a href="https://tutolibro.org/2020/06/26/libreoffice-calc-python-programming-part-6-type-of-a-cell-content/"> my previous episode</a> of this series).<br>Note that a Tuple in Python is &#8216;immutable&#8217;, it means that we cannot change its content once it has been defined. It is important to know and I&#8217;ll show you how to work with tuples easily.<br>So let&#8217;s get Started.</p>



<h4 class="wp-block-heading">Here is the plan for this tutorial:</h4>



<ul class="wp-block-list">
<li>Set the context for global variables</li>



<li>Get the Range of Addresses</li>



<li>Get the data from a range of Cells by Position</li>



<li>Get the data from a range of Cells by Name</li>



<li>Store Cells content in an Tuple of Data</li>
</ul>



<h4 class="wp-block-heading">Set the context for global variables</h4>



<pre class="wp-block-verse">Note: you can start from the same script as the <a href="https://tutolibro.org/2020/06/26/libreoffice-calc-python-programming-part-6-type-of-a-cell-content/">previous tutorial</a> (part 6 - Cells Types ).</pre>



<p>Starting with our usual context() function that stores desktop , model and active_sheet at a global scope:</p>



<pre class="wp-block-code"><code>def context():
    
    # set global variables for context
    
    global desktop
    global model
    global active_sheet
    
    # get the doc from the scripting context 
    # which is made available to all scripts
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    
    # access the active sheet
    active_sheet = model.CurrentController.ActiveSheet</code></pre>



<h4 class="wp-block-heading">Get the Range of Addresses</h4>



<p>In our <strong>main</strong> function we start by calling <strong>context</strong>(), then we need to get the Addresses of the cells .</p>



<pre class="wp-block-code"><code>def main():
    
    # call function context()
    context()
    
    # get the range of addresses from selection
    oSelection = model.getCurrentSelection()
    oArea = oSelection.getRangeAddress()</code></pre>



<p>The method <strong>getRangeAddress</strong>() returns a <strong>CellRangeAddress</strong>.<br> A <strong>CellRangeAddress</strong> is a Struct (short for Structure). It has the following Attributes:</p>



<p><strong>Sheet, StartColumn, StartRow, EndRow, EndColumn.</strong></p>



<p>We don&#8217;t really need the <strong>Sheet</strong> index yet as we are only working on the current sheet. But we need the 4 other attributes. They correspond to the top-left and bottom-right cells of what we have selected with the mouse.</p>



<p>I strongly advise you to check <a rel="noreferrer noopener" href="https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1sheet_1_1XCellRangeData.html#details" target="_blank"><strong>XCellRangeAddress</strong></a> and explore the LibreOffice API. It is actually a really good way to discover the different methods and attributes that you can use.</p>



<p>The next step is to get all necessary cell references to retrieve data from a Range of Cells. We can do that now that we have our <strong>oArea</strong> object variable. </p>



<pre class="wp-block-code"><code>    # store the attribute of CellRandeAddress 
    nLeft = oArea.StartColumn
    nTop = oArea.StartRow
    nRight = oArea.EndColumn
    nBottom = oArea.EndRow
    #(note: could the attribute directly instead of using intermediary variable)</code></pre>



<pre class="wp-block-verse">Note that although we could use the <strong>oArea</strong> attributes, storing them in variables with relevant names makes the program/script more readable.</pre>



<h4 class="wp-block-heading">Get the data from a range of Cells by Position</h4>



<p>Now we can call function <strong>getCellRangeByPosition</strong> to returns a &#8216;sub-range&#8217; of the active sheet. Understand that the active sheet itself is a range of cells that is much bigger.<br>That &#8216;sub-range&#8217; is the range of Selected Cells from where we are going to extract data. I am calling that range <strong>oRangeSource</strong>.</p>



<pre class="wp-block-code"><code>    # get data from the source
    oRangeSource = active_sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom)</code></pre>



<p>Here is an example of a selected range of cells in LibreOffice:</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="305" height="169" src="https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-1.png" alt="" class="wp-image-1014" srcset="https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-1.png 305w, https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-1-300x166.png 300w" sizes="(max-width: 305px) 100vw, 305px" /><figcaption class="wp-element-caption">From Top-Left to Bottom-Right</figcaption></figure>



<h4 class="wp-block-heading">Get the data from a range of Cells by Name</h4>



<p>In this tutorial we are using variables to get the Range of Cells. We could also use arbitrary values corresponding to the Top-left and Bottom-Right cells of the range like:</p>



<pre class="wp-block-code"><code>oRangeSource = active_sheet.getCellRangeByPosition(0, 0, 2, 9)</code></pre>



<p>That set of parameters (0, 0, 2, 9) means that we are getting the range from cell(0,0) to cell(2,9).<br>In some cases it is easier to refer the cells by name. With names instead of positions the range (0,0,2,9) would be from cell &#8220;A1&#8221; to cell &#8220;C10&#8221;.</p>



<p>If you work with a range of cells by name it is then much easier to use the dedicated function <strong>getCellRangeByName</strong>:</p>



<pre class="wp-block-code"><code>    # example by name:
    oRangeSource = active_sheet.getCellRangeByName('A1:C10')</code></pre>



<p>You would define the range of cells the same way you do it in formulas: <strong>&#8216;A1:C10</strong>&#8216;.</p>



<p>Using range by position is much easier in programs where the ranges are not always the same and can be dynamically changed. It makes it much more flexible to work with, especially if you need to run loops on the cells.</p>



<h4 class="wp-block-heading">Store Cells content in an Tuple of Data</h4>



<p>This is a key operation.<br>The function <strong>getDataArray</strong> extracts the content of the cells within a range and stores that content in a tuple. And from there we will be able to use that content easily with Python. Here is the simple line of code needed to do that:</p>



<pre class="wp-block-code"><code>    # get data from the Range of cells and store in a tuple
    oDataSource = oRangeSource.getDataArray()</code></pre>



<pre class="wp-block-verse">Note: A <strong>print</strong> statement here would be helpful to check how the tuple of data looks like. To get the APSO console <a href="https://tutolibro.org/2020/02/24/libreoffice-calc-python-programming-part-4-using-apso-console-to-print-text/">check part 4 </a> of this series of tutorials).</pre>



<pre class="wp-block-code"><code>    # print to console
    print(oRangeSource)</code></pre>



<p>Here is an example of what you would get:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="715" height="306" src="https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-0.png" alt="" class="wp-image-1009" srcset="https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-0.png 715w, https://tutolibro.org/wp-content/uploads/2020/07/lopy-part7-0-300x128.png 300w" sizes="(max-width: 715px) 100vw, 715px" /><figcaption class="wp-element-caption">From a LibreOffice Range of Cells to a Python&#8217;s Tuple!</figcaption></figure>



<p>The Tuple produced is actually a tuple of tuples:</p>



<p>((1.0, &#8216;C&#8217;), (2.0, &#8216;D&#8217;), (&#8216;A&#8217;, 3.0), (&#8216;B&#8217;, 4.0))</p>



<p>As you can see each tuple inside the big tuple stores a row of data.<br>If you look closer, for example if you look at the tuple for the first row:</p>



<p>(1.0,&#8217;C&#8217;)</p>



<p>You will see that the 1.0 has no quote where the &#8216;C&#8217; has quotes. This means that the types of the data within the cells have been preserved.<br>A number in LibreOffice remains a number in Python, and string remains a string. In fact the function <strong>getDataArray</strong>() returns a tuple of tuples with data of a type <strong>Double</strong> or <strong>String</strong>. Double is a type for any decimal numbers.</p>



<p>Now here is the full code for this tutorial:</p>



<pre class="wp-block-code"><code>def context():
    
    # set global variables for context
    
    global desktop
    global model
    global active_sheet
    
    # get the doc from the scripting context 
    # which is made available to all scripts
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    
    # access the active sheet
    active_sheet = model.CurrentController.ActiveSheet
    
def main():
    
    # call function context()
    context()
    
    # get the range of addresses from selection
    oSelection = model.getCurrentSelection()
    oArea = oSelection.getRangeAddress()

    # store the attribute of CellRangeAddress 
    nLeft = oArea.StartColumn
    nTop = oArea.StartRow
    nRight = oArea.EndColumn
    nBottom = oArea.EndRow
    #(note: could the attribute directly instead of using intermediary variable)
    
    # get the Cell Range 
    oRangeSource = active_sheet.getCellRangeByPosition(nLeft, nTop, nRight, nBottom)
    
    # example by name:
    # ~ oRangeSource = active_sheet.getCellRangeByName('A1:C10')
    
    # get data from the Range of cells and store in a tuple
    oDataSource = oRangeSource.getDataArray()
    
    # print to console
    print(oDataSource)</code></pre>



<p>On gitHub: <a href="https://github.com/Gweno/tutolibro.tech/tree/master/lopy/part7" target="_blank" rel="noreferrer noopener">https://github.com/Gweno/tutolibro.tech/tree/master/lopy/part7</a></p>



<p>To make it easier to test my scripts I usually assign them to a combination of keys like CTRL + 0. Learn how to do it on <a href="https://tutolibro.org/2020/03/11/libreoffice-calc-python-programming-annex-1-assign-a-python-macro-to-a-key/">this post</a>.</p>



<p>In the next tutorials we will actually do something with the tuple created here and then play a little bit the data inside.</p>



<pre class="wp-block-verse">Please leave a comment to let me know what you think about this tutorial 
or if you had any issues going through it. Getting your comments helps 
me a lot to make the next tutorials better! Thank you!</pre>



<p>If you like this tutorial, you could <a href="https://buymeacoffee.com/tutolibro" data-type="link" data-id="https://buymeacoffee/tutolibro" target="_blank" rel="noreferrer noopener">buy me a coffee</a> to help me continue writing add-free tutorials.</p>



<p>Thank you!</p>



<div class="wp-block-group is-content-justification-space-between is-nowrap is-layout-flex wp-container-core-group-is-layout-0dfbf163 wp-block-group-is-layout-flex">

</div>
]]></content:encoded>
					
					<wfw:commentRss>https://tutolibro.org/2020/07/10/libreoffice-calc-python-programming-part-7-from-cells-range-to-python-tuple/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">998</post-id>	</item>
	</channel>
</rss>
