Table

Struct Table 

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

The Table struct represents an Excel worksheet table.

Tables in Excel are a way of grouping a range of cells into a single entity that has common formatting or that can be referenced in formulas. In calamine, tables can be read and converted to a data Range for further processing.

Calamine does not automatically load Table data from a workbook to avoid unnecessary overhead. Instead you must explicitly load the Table data using the Xlsx::load_tables() method. Once the tables have been loaded the following methods can be used to extract and work with individual tables:

Note, these methods are only available for the Xlsx struct since Tables are a feature of the xlsx/xlsb format. They are not currently implemented for Xlsb.

Once you have a Table instance, you can access its properties and data using the methods below.

§Examples

An example of reading the data from an Excel worksheet Table using the calamine crate.

The sample Excel file inventory-table.xlsx contains a single sheet named “Sheet1” with the following data laid out in a worksheet Table called “Table1”:

 _____________________________________________________________
|         ||                |                |                |
|         ||       A        |       B        |       C        |
|_________||________________|________________|________________|
|    1    || Item           | Type           | Quantity       |
|_________||________________|________________|________________|
|    2    ||              1 | Apple          |             50 |
|_________||________________|________________|________________|
|    3    ||              2 | Banana         |            200 |
|_________||________________|________________|________________|
|    4    ||              3 | Orange         |             60 |
|_________||________________|________________|________________|
|    5    ||              4 | Pear           |            100 |
|_________||________________|________________|________________|
|_          __________________________________________________|
  \ Sheet1 /
    ------
use calamine::{open_workbook, Error, 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")?;

    // Check the table's name.
    let table_name = table.name();
    assert_eq!(table_name, "Table1");

    // Check that it came from Sheet1.
    let sheet_name = table.sheet_name();
    assert_eq!(sheet_name, "Sheet1");

    // Get the table column headers.
    let columns_headers = table.columns();
    assert_eq!(columns_headers, vec!["Item", "Type", "Quantity"]);

    // Get the table data range (without the headers).
    let data = table.data();

    // Iterate over the rows of the data range.
    for (row_num, row) in data.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}");
        }
        println!();
    }

    Ok(())
}

Output in relative coordinates:

(0, 0): 1
(0, 1): Apple
(0, 2): 50

(1, 0): 2
(1, 1): Banana
(1, 2): 200

(2, 0): 3
(2, 1): Orange
(2, 2): 60

(3, 0): 4
(3, 1): Pear
(3, 2): 100

Implementations§

Source§

impl<T> Table<T>

Source

pub fn name(&self) -> &str

Get the name of the table.

Tables in Excel have sequentially assigned names like “Table1”, “Table2”, etc. but can also have used assigned names.

§Examples

An example of getting the name of an Excel worksheet Table.

use calamine::{open_workbook, Error, 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")?;

    // Check the table's name.
    let table_name = table.name();
    assert_eq!(table_name, "Table1");

    Ok(())
}
Source

pub fn sheet_name(&self) -> &str

Get the name of the parent worksheet for a table.

This method returns the name of the parent worksheet that contains the table.

§Examples

An example of getting the parent worksheet name for an Excel worksheet Table.

use calamine::{open_workbook, Error, 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")?;

    // Check that it came from Sheet1.
    let sheet_name = table.sheet_name();
    assert_eq!(sheet_name, "Sheet1");

    Ok(())
}
Source

pub fn columns(&self) -> &[String]

Get the header names of the table columns.

This method returns a slice of strings representing the names of the column headers in the table.

In Excel table headers can be hidden but the table will still have column header names.

§Examples

An example of getting the column headers for an Excel worksheet Table.

use calamine::{open_workbook, Error, 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")?;

    // Get the table column headers.
    let columns_headers = table.columns();
    assert_eq!(columns_headers, vec!["Item", "Type", "Quantity"]);

    Ok(())
}
Source

pub fn data(&self) -> &Range<T>

Get a range representing the data from the table

This method returns a reference to the data Range of the table,

Note that the data range excludes the column headers.

§Examples

An example of getting the data range of an Excel worksheet Table.

use calamine::{open_workbook, Data, Error, 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")?;

    // Get the data range of the table.
    let data_range = table.data();

    // 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(())
}

Trait Implementations§

Source§

impl<T: Clone> Clone for Table<T>

Source§

fn clone(&self) -> Table<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 Table<T>

Source§

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

Formats the value using the given formatter. 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.

Auto Trait Implementations§

§

impl<T> Freeze for Table<T>

§

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

§

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

§

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

§

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

§

impl<T> UnwindSafe for Table<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<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.