Range

Struct Range 

Source
pub struct Range<T> { /* private fields */ }
Expand description

A struct which represents an area of cells and the data within it.

Ranges are used by calamine to represent an area of data in a worksheet. A Range is a rectangular area of cells defined by its start and end positions.

A Range is constructed with absolute positions in the form of (row, column). The start position for the absolute positioning is the cell (0, 0) or A1. For the example range “B3:C6”, shown below, the start position is (2, 1) and the end position is (5, 2). Within the range, the cells are indexed with relative positions where (0, 0) is the start cell. In the example below the relative positions for the start and end cells are (0, 0) and (3, 1) respectively.

 ______________________________________________________________________________
|         ||                |                |                |                |
|         ||       A        |       B        |       C        |       D        |
|_________||________________|________________|________________|________________|
|    1    ||                |                |                |                |
|_________||________________|________________|________________|________________|
|    2    ||                |                |                |                |
|_________||________________|________________|________________|________________|
|    3    ||                | (2, 1), (0, 0) |                |                |
|_________||________________|________________|________________|________________|
|    4    ||                |                |                |                |
|_________||________________|________________|________________|________________|
|    5    ||                |                |                |                |
|_________||________________|________________|________________|________________|
|    6    ||                |                | (5,2), (3, 1)  |                |
|_________||________________|________________|________________|________________|
|    7    ||                |                |                |                |
|_________||________________|________________|________________|________________|
|_          ___________________________________________________________________|
  \ Sheet1 /
    ------

A Range contains a vector of cells of of generic type T which implement the CellType trait. The values are stored in a row-major order.

Implementations§

Source§

impl<T: CellType> Range<T>

Source

pub fn new(start: (u32, u32), end: (u32, u32)) -> Range<T>

Creates a new Range with default values.

Create a new Range with the given start and end positions. The positions are in worksheet absolute coordinates, i.e. (0, 0) is cell A1.

The range is populated with default values of type T.

When possible, use the more efficient Range::from_sparse() constructor.

§Parameters
  • start: The zero indexed (row, column) tuple.
  • end: The zero indexed (row, column) tuple.
§Panics

Panics if start > end.

§Examples

An example of creating a new calamine Range.

use calamine::{Data, Range};

// Create a 8x1 Range.
let range: Range<Data> = Range::new((2, 2), (9, 2));

assert_eq!(range.width(), 1);
assert_eq!(range.height(), 8);
assert_eq!(range.cells().count(), 8);
assert_eq!(range.used_cells().count(), 0);
Source

pub fn empty() -> Range<T>

Creates a new empty Range.

Creates a new Range with start and end positions both set to (0, 0) and with an empty inner vector. An empty range can be expanded by adding data.

§Examples

An example of creating a new empty calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::empty();

assert!(range.is_empty());
Source

pub fn start(&self) -> Option<(u32, u32)>

Get top left cell position of a Range.

Get the top left cell position of a range in absolute (row, column) coordinates.

Returns None if the range is empty.

§Examples

An example of getting the start position of a calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::new((2, 3), (9, 3));

assert_eq!(range.start(), Some((2, 3)));
Source

pub fn end(&self) -> Option<(u32, u32)>

Get bottom right cell position of a Range.

Get the bottom right cell position of a range in absolute (row, column) coordinates.

Returns None if the range is empty.

§Examples

An example of getting the end position of a calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::new((2, 3), (9, 3));

assert_eq!(range.end(), Some((9, 3)));
Source

pub fn width(&self) -> usize

Get the column width of a Range.

The width is defined as the number of columns between the start and end positions.

§Examples

An example of getting the column width of a calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::new((2, 3), (9, 3));

assert_eq!(range.width(), 1);
Source

pub fn height(&self) -> usize

Get the row height of a Range.

The height is defined as the number of rows between the start and end positions.

§Examples

An example of getting the row height of a calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::new((2, 3), (9, 3));

assert_eq!(range.height(), 8);
Source

pub fn get_size(&self) -> (usize, usize)

Get size of a Range in (height, width) format.

§Examples

An example of getting the (height, width) size of a calamine Range.

use calamine::{Data, Range};

let range: Range<Data> = Range::new((2, 3), (9, 3));

assert_eq!(range.get_size(), (8, 1));
Source

pub fn is_empty(&self) -> bool

Check if a Range is empty.

§Examples

An example of checking if a calamine Range is empty.

use calamine::{Data, Range};

let range: Range<Data> = Range::empty();

assert!(range.is_empty());
Source

pub fn from_sparse(cells: Vec<Cell<T>>) -> Range<T>

Creates a Range from a sparse vector of cells.

The Range::from_sparse() constructor can be used to create a Range from a vector of Cell data. This is slightly more efficient than creating a range with Range::new() and then setting the values.

§Parameters
  • cells: A vector of Cell elements.
§Examples

An example of creating a new calamine Range for a sparse vector of Cells.

use calamine::{Cell, Data, Range};

let cells = vec![
    Cell::new((2, 2), Data::Int(1)),
    Cell::new((5, 2), Data::Int(1)),
    Cell::new((9, 2), Data::Int(1)),
];

let range = Range::from_sparse(cells);

assert_eq!(range.width(), 1);
assert_eq!(range.height(), 8);
assert_eq!(range.cells().count(), 8);
assert_eq!(range.used_cells().count(), 3);
Source

pub fn set_value(&mut self, absolute_position: (u32, u32), value: T)

Set a value at an absolute position in a Range.

This method sets a value in the range at the given absolute position (relative to A1).

Try to avoid this method as much as possible and prefer initializing the Range with the Range::from_sparse() constructor.

§Parameters
  • absolute_position: The absolute position, relative to A1, in the form of (row, column). It must be greater than or equal to the start position of the range. If the position is greater than the end of the range the structure will be resized to accommodate the new end position.
§Panics

If absolute_position.0 < self.start.0 || absolute_position.1 < self.start.1

§Examples

An example of setting a value in a calamine Range.

use calamine::{Data, Range};

let mut range = Range::new((0, 0), (5, 2));

// The initial range is empty.
assert_eq!(range.get_value((2, 1)), Some(&Data::Empty));

// Set a value at a specific position.
range.set_value((2, 1), Data::Float(1.0));

// The value at the specified position should now be set.
assert_eq!(range.get_value((2, 1)), Some(&Data::Float(1.0)));
Source

pub fn get_value(&self, absolute_position: (u32, u32)) -> Option<&T>

Get a value at an absolute position in a Range.

If the absolute_position is out of range, returns None, otherwise returns the cell value. The coordinate format is (row, column) relative to A1.

For relative positions see the Range::get() method.

§Parameters
  • absolute_position: The absolute position, relative to A1, in the form of (row, column).
§Examples

An example of getting a value in a calamine Range.

use calamine::{Data, Range};

let range = Range::new((1, 1), (5, 5));

// Get the value for a cell in the range.
assert_eq!(range.get_value((2, 2)), Some(&Data::Empty));

// Get the value for a cell outside the range.
assert_eq!(range.get_value((0, 0)), None);
Source

pub fn get(&self, relative_position: (usize, usize)) -> Option<&T>

Get a value at a relative position in a Range.

If the relative_position is out of range, returns None, otherwise returns the cell value. The coordinate format is (row, column) relative to (0, 0) in the range.

For absolute cell positioning see the Range::get_value() method.

§Parameters
  • relative_position: The position relative to the index (0, 0) in the range.
§Examples

An example of getting a value in a calamine Range, using relative positioning.

use calamine::{Data, Range};

let mut range = Range::new((1, 1), (5, 5));

// Set a cell value using the cell absolute position.
range.set_value((2, 3), Data::Int(123));

// Get the value using the range relative position.
assert_eq!(range.get((1, 2)), Some(&Data::Int(123)));
Source

pub fn rows(&self) -> Rows<'_, T>

Get an iterator over the rows of a Range.

§Examples

An example of using a Row iterator with a calamine Range.

use calamine::{Cell, Data, Range};

let cells = vec![
    Cell::new((1, 1), Data::Int(1)),
    Cell::new((1, 2), Data::Int(2)),
    Cell::new((3, 1), Data::Int(3)),
];

// Create a Range from the cells.
let range = Range::from_sparse(cells);

// Iterate over the rows of the range.
for (row_num, row) in range.rows().enumerate() {
    for (col_num, data) in row.iter().enumerate() {
        // Print the data in each cell of the row.
        println!("({row_num}, {col_num}): {data}");
    }
}

Output in relative coordinates:

(0, 0): 1
(0, 1): 2
(1, 0):
(1, 1):
(2, 0): 3
(2, 1):
Source

pub fn used_cells(&self) -> UsedCells<'_, T>

Get an iterator over the used cells in a Range.

This method returns an iterator over the used cells in a range. The “used” cells are defined as the cells that have a value other than the default value for T. The iterator returns tuples of (row, column, value) for each used cell. The row and column are relative/index values rather than absolute cell positions.

§Examples

An example of iterating over the used cells in a calamine Range.

use calamine::{Cell, Data, Range};

let cells = vec![
    Cell::new((1, 1), Data::Int(1)),
    Cell::new((1, 2), Data::Int(2)),
    Cell::new((3, 1), Data::Int(3)),
];

// Create a Range from the cells.
let range = Range::from_sparse(cells);

// Iterate over the used cells in the range.
for (row, col, data) in range.used_cells() {
    println!("({row}, {col}): {data}");
}

Output:

(0, 0): 1
(0, 1): 2
(2, 0): 3
Source

pub fn cells(&self) -> Cells<'_, T>

Get an iterator over all the cells in a Range.

This method returns an iterator over all the cells in a range, including those that are empty. The iterator returns tuples of (row, column, value) for each cell. The row and column are relative/index values rather than absolute cell positions.

§Examples

An example of iterating over the used cells in a calamine Range.

use calamine::{Cell, Data, Range};

let cells = vec![
    Cell::new((1, 1), Data::Int(1)),
    Cell::new((1, 2), Data::Int(2)),
    Cell::new((3, 1), Data::Int(3)),
];

// Create a Range from the cells.
let range = Range::from_sparse(cells);

// Iterate over the cells in the range.
for (row, col, data) in range.cells() {
    println!("({row}, {col}): {data}");
}

Output:

(0, 0): 1
(0, 1): 2
(1, 0):
(1, 1):
(2, 0): 3
(2, 1):
Source

pub fn deserialize<'a, D>( &'a self, ) -> Result<RangeDeserializer<'a, T, D>, DeError>

Build a RangeDeserializer for a Range.

This method returns a RangeDeserializer that can be used to deserialize the data in the range.

§Errors
  • DeError if the range cannot be deserialized.
§Examples

An example of creating a deserializer fora calamine Range.

The sample Excel file temperature.xlsx contains a single sheet named “Sheet1” with the following data:

 ____________________________________________
|         ||                |                |
|         ||       A        |       B        |
|_________||________________|________________|
|    1    || label          | value          |
|_________||________________|________________|
|    2    || celsius        | 22.2222        |
|_________||________________|________________|
|    3    || fahrenheit     | 72             |
|_________||________________|________________|
|_          _________________________________|
  \ Sheet1 /
    ------
use calamine::{open_workbook, Error, Reader, Xlsx};

fn main() -> Result<(), Error> {
    let path = "tests/temperature.xlsx";

    // Open the workbook.
    let mut workbook: Xlsx<_> = open_workbook(path)?;

    // Get the data range from the first sheet.
    let sheet_range = workbook.worksheet_range("Sheet1")?;

    // Get an iterator over data in the range.
    let mut iter = sheet_range.deserialize()?;

    // Get the next record in the range. The first row is assumed to be the
    // header.
    if let Some(result) = iter.next() {
        let (label, value): (String, f64) = result?;

        assert_eq!(label, "celsius");
        assert_eq!(value, 22.2222);

        Ok(())
    } else {
        Err(From::from("Expected at least one record but got none"))
    }
}
Source

pub fn range(&self, start: (u32, u32), end: (u32, u32)) -> Range<T>

Build a new Range out of the current range.

This method returns a new Range with cloned data. In general it is used to get a subset of an existing range. However, if the new range is larger than the existing range the new cells will be filled with default values.

§Examples

An example of getting a sub range of a calamine Range.

use calamine::{Data, Range};

// Create a range with some values.
let mut a = Range::new((1, 1), (3, 3));
a.set_value((1, 1), Data::Bool(true));
a.set_value((2, 2), Data::Bool(true));
a.set_value((3, 3), Data::Bool(true));

// Get a sub range of the main range.
let b = a.range((1, 1), (2, 2));
assert_eq!(b.get_value((1, 1)), Some(&Data::Bool(true)));
assert_eq!(b.get_value((2, 2)), Some(&Data::Bool(true)));

// Get a larger range with default values.
let c = a.range((0, 0), (5, 5));
assert_eq!(c.get_value((0, 0)), Some(&Data::Empty));
assert_eq!(c.get_value((3, 3)), Some(&Data::Bool(true)));
assert_eq!(c.get_value((5, 5)), Some(&Data::Empty));
Source§

impl<T: CellType + Display> Range<T>

Source

pub fn headers(&self) -> Option<Vec<String>>

Get headers for a Range.

This method returns the first row of the range as an optional vector of strings. The data type T in the range must support the ToString trait.

§Examples

An example of getting the header row of a calamine Range.

use calamine::{Data, Range};

// Create a range with some values.
let mut range = Range::new((0, 0), (5, 2));
range.set_value((0, 0), Data::String(String::from("a")));
range.set_value((0, 1), Data::Int(1));
range.set_value((0, 2), Data::Bool(true));

// Get the headers of the range.
let headers = range.headers();

assert_eq!(
    headers,
    Some(vec![
        String::from("a"),
        String::from("1"),
        String::from("true")
    ])
);

Trait Implementations§

Source§

impl<T: Clone> Clone for Range<T>

Source§

fn clone(&self) -> Range<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Range<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for Range<T>

Source§

fn default() -> Range<T>

Returns the “default value” for a type. Read more
Source§

impl<T: CellType> From<Table<T>> for Range<T>

Convert a Table<T> into a Range<T>.

§Examples

An example of getting the data range of an Excel worksheet Table via the From/Into trait.

use calamine::{open_workbook, Data, Error, Range, Xlsx};

fn main() -> Result<(), Error> {
    let path = format!("{}/tests/inventory-table.xlsx", env!("CARGO_MANIFEST_DIR"));

    // Open the workbook.
    let mut workbook: Xlsx<_> = open_workbook(path)?;

    // Load the tables in the workbook.
    workbook.load_tables()?;

    // Get the table by name.
    let table = workbook.table_by_name("Table1")?;

    // Convert the table into a data range using the `From/Into` trait.
    let data_range: Range<Data> = table.into();

    // Check one of the values in the data range. Note the relative
    // positioning within the range returned by the `get()` method.
    assert_eq!(
        data_range.get((0, 1)),
        Some(&Data::String("Apple".to_string()))
    );

    Ok(())
}
Source§

fn from(table: Table<T>) -> Range<T>

Converts to this type from the input type.
Source§

impl<T: CellType> Index<(usize, usize)> for Range<T>

Implementation of the Index trait for Range cells.

§Examples

An example of cell indexing for a calamine Range.

use calamine::{Data, Range};

// Create a range with a value.
let mut range = Range::new((1, 1), (3, 3));
range.set_value((2, 2), Data::Int(123));

// Get the value via cell indexing.
assert_eq!(range[(1, 1)], Data::Int(123));
Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, index: (usize, usize)) -> &T

Performs the indexing (container[index]) operation. Read more
Source§

impl<T: CellType> Index<usize> for Range<T>

Implementation of the Index trait for Range rows.

§Examples

An example of row indexing for a calamine Range.

use calamine::{Data, Range};

// Create a range with a value.
let mut range = Range::new((1, 1), (3, 3));
range.set_value((2, 2), Data::Int(123));

// Get the second row via indexing.
assert_eq!(range[1], [Data::Empty, Data::Int(123), Data::Empty]);
Source§

type Output = [T]

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &[T]

Performs the indexing (container[index]) operation. Read more
Source§

impl<T: CellType> IndexMut<(usize, usize)> for Range<T>

Implementation of the IndexMut trait for Range cells.

§Examples

An example of mutable cell indexing for a calamine Range.

use calamine::{Data, Range};

// Create a new empty range.
let mut range = Range::new((1, 1), (3, 3));

// Set a value in the range using cell indexing.
range[(1, 1)] = Data::Int(123);

// Test the value was set correctly.
assert_eq!(range.get((1, 1)), Some(&Data::Int(123)));
Source§

fn index_mut(&mut self, index: (usize, usize)) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<T: CellType> IndexMut<usize> for Range<T>

Implementation of the IndexMut trait for Range rows.

Source§

fn index_mut(&mut self, index: usize) -> &mut [T]

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<T: PartialEq> PartialEq for Range<T>

Source§

fn eq(&self, other: &Range<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Eq> Eq for Range<T>

Source§

impl<T> StructuralPartialEq for Range<T>

Auto Trait Implementations§

§

impl<T> Freeze for Range<T>

§

impl<T> RefUnwindSafe for Range<T>
where T: RefUnwindSafe,

§

impl<T> Send for Range<T>
where T: Send,

§

impl<T> Sync for Range<T>
where T: Sync,

§

impl<T> Unpin for Range<T>
where T: Unpin,

§

impl<T> UnwindSafe for Range<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.