Struct prettytable::Table

source ·
pub struct Table { /* private fields */ }
Expand description

An owned printable table

Implementations§

Create a table from a CSV string

For more customisability use from_csv()

Examples found in repository?
examples/csv.rs (lines 19-23)
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
fn main() {
    use prettytable::Table;

    let table = Table::from_csv_string(
        "ABC,DEFG,HIJKLMN\n\
                                        foobar,bar,foo\n\
                                        foobar2,bar2,foo2",
    )
    .unwrap();
    table.printstd();

    println!("");
    println!(
        "{}",
        String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
    );
}

Create a table from a CSV file

For more customisability use from_csv()

Create a table from a CSV reader

Write the table to the specified writer.

Examples found in repository?
examples/csv.rs (line 30)
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
fn main() {
    use prettytable::Table;

    let table = Table::from_csv_string(
        "ABC,DEFG,HIJKLMN\n\
                                        foobar,bar,foo\n\
                                        foobar2,bar2,foo2",
    )
    .unwrap();
    table.printstd();

    println!("");
    println!(
        "{}",
        String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
    );
}

Write the table to the specified writer.

This allows for format customisation.

Create an empty table

Examples found in repository?
examples/basic.rs (line 22)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let mut table = Table::new();
    table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
    table.add_row(row!["foobar", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        Cell::new("bar2"),
        Cell::new("foo2"),
    ]));
    table.printstd();
    println!("Modified : ");
    table.set_element("new_foo", 2, 1).unwrap();
    table.printstd();

    // The same table can be built the following way :
    let _table = table!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );

    // Or directly print it like this
    let _table = ptable!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );
}
More examples
Hide additional examples
examples/style.rs (line 8)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn main() {
    let _ = table!();
    let mut table = Table::new();
    // Add style to a cell
    table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
    // Add style to a full row
    table.add_row(row![FY => "styled", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        // Create a cell with a red foreground color
        Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
        // Create a cell with red foreground color, yellow background color, with bold characters
        Cell::new("foo2").style_spec("FrByb"),
        // Using the cell! macro
        cell!(Fr->"red"),
    ]));

    table.printstd();

    // Print a table with some styles on it :
    // FrBybl means : Foregound red, Background yellow, bold, left align
    ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);

    // You can also apply style to full rows :
    let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
    // Set a title line, with all text centered in the cell
    table.set_titles(row![c => "Title 1", "Title 2"]);
    table.printstd();
}

Create a table initialized with rows

Change the table format. Eg : Separators

Examples found in repository?
examples/formatting.rs (line 15)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
fn main() {
    let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
    table.set_titles(row!["Title 1", "Title 2"]);

    // Print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // +-------------+------------+
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("FORMAT_NO_LINESEP_WITH_TITLE :");
    table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
    table.printstd();
    println!("");

    // Print
    // -------------------------
    //  Title 1      Title 2
    // =========================
    //  Value 1      Value 2
    // -------------------------
    //  Value three  Value four
    // -------------------------
    println!("FORMAT_NO_COLSEP :");
    table.set_format(*format::consts::FORMAT_NO_COLSEP);
    table.printstd();
    println!("");

    // Print
    // +-------------------------+
    // | Title 1      Title 2    |
    // +=========================+
    // | Value 1      Value 2    |
    // | Value three  Value four |
    // +-------------------------+
    println!("FORMAT_BORDERS_ONLY :");
    table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
    table.printstd();
    println!("");

    // Custom format can be implemented using `prettytable::format::FormatBuilder`
    // Example to print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("Custom :");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('|')
            .borders('|')
            .separators(
                &[format::LinePosition::Top, format::LinePosition::Bottom],
                format::LineSeparator::new('-', '+', '+', '+'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode
    // Example to print
    // ┌─────────────┬────────────┐
    // │ Title 1     │ Title 2    │
    // ├─────────────┼────────────┤
    // │ Value 1     │ Value 2    │
    // ├─────────────┼────────────┤
    // │ Value three │ Value four │
    // └─────────────┴────────────┘
    println!("With unicode:");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('│')
            .borders('│')
            .separators(
                &[format::LinePosition::Top],
                format::LineSeparator::new('─', '┬', '┌', '┐'),
            )
            .separators(
                &[format::LinePosition::Intern],
                format::LineSeparator::new('─', '┼', '├', '┤'),
            )
            .separators(
                &[format::LinePosition::Bottom],
                format::LineSeparator::new('─', '┴', '└', '┘'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode and different padding
    // Example to print
    // ┌───────────────┬──────────────┐
    // │  Title 1      │  Title 2     │
    // ├───────────────┼──────────────┤
    // │  Value 1      │  Value 2     │
    // ├───────────────┼──────────────┤
    // │  Value three  │  Value four  │
    // └───────────────┴──────────────┘
    // Change individual format settings
    println!("With unicode and padding:");
    table.get_format().padding(2, 2);
    table.printstd();
}

Get a mutable reference to the internal format

Examples found in repository?
examples/formatting.rs (line 107)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
fn main() {
    let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
    table.set_titles(row!["Title 1", "Title 2"]);

    // Print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // +-------------+------------+
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("FORMAT_NO_LINESEP_WITH_TITLE :");
    table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
    table.printstd();
    println!("");

    // Print
    // -------------------------
    //  Title 1      Title 2
    // =========================
    //  Value 1      Value 2
    // -------------------------
    //  Value three  Value four
    // -------------------------
    println!("FORMAT_NO_COLSEP :");
    table.set_format(*format::consts::FORMAT_NO_COLSEP);
    table.printstd();
    println!("");

    // Print
    // +-------------------------+
    // | Title 1      Title 2    |
    // +=========================+
    // | Value 1      Value 2    |
    // | Value three  Value four |
    // +-------------------------+
    println!("FORMAT_BORDERS_ONLY :");
    table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
    table.printstd();
    println!("");

    // Custom format can be implemented using `prettytable::format::FormatBuilder`
    // Example to print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("Custom :");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('|')
            .borders('|')
            .separators(
                &[format::LinePosition::Top, format::LinePosition::Bottom],
                format::LineSeparator::new('-', '+', '+', '+'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode
    // Example to print
    // ┌─────────────┬────────────┐
    // │ Title 1     │ Title 2    │
    // ├─────────────┼────────────┤
    // │ Value 1     │ Value 2    │
    // ├─────────────┼────────────┤
    // │ Value three │ Value four │
    // └─────────────┴────────────┘
    println!("With unicode:");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('│')
            .borders('│')
            .separators(
                &[format::LinePosition::Top],
                format::LineSeparator::new('─', '┬', '┌', '┐'),
            )
            .separators(
                &[format::LinePosition::Intern],
                format::LineSeparator::new('─', '┼', '├', '┤'),
            )
            .separators(
                &[format::LinePosition::Bottom],
                format::LineSeparator::new('─', '┴', '└', '┘'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode and different padding
    // Example to print
    // ┌───────────────┬──────────────┐
    // │  Title 1      │  Title 2     │
    // ├───────────────┼──────────────┤
    // │  Value 1      │  Value 2     │
    // ├───────────────┼──────────────┤
    // │  Value three  │  Value four  │
    // └───────────────┴──────────────┘
    // Change individual format settings
    println!("With unicode and padding:");
    table.get_format().padding(2, 2);
    table.printstd();
}

Get the number of rows

Check if the table is empty

Set the optional title lines

Examples found in repository?
examples/slices.rs (line 12)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
fn main() {
    let mut table = table![
        [0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4],
        [5, 5, 5]
    ];
    table.set_titles(row!["t1", "t2", "t3"]);

    let slice = table.slice(..);
    let slice = slice.slice(2..);
    let slice = slice.slice(..3);

    /*
        Will print
        +----+----+----+
        | t1 | t2 | t3 |
        +====+====+====+
        | 2  | 2  | 2  |
        +----+----+----+
        | 3  | 3  | 3  |
        +----+----+----+
        | 4  | 4  | 4  |
        +----+----+----+
    */
    slice.printstd();

    // This is equivalent to
    let slice = table.slice(2..5);
    slice.printstd();
}
More examples
Hide additional examples
examples/span.rs (lines 23-27)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
    /*
        The following code will output

        +---------------+---------------+--------------+
        |         A table with horizontal span         |
        +===============+===============+==============+
        | This is a cell with span of 2 | span of 1    |
        +---------------+---------------+--------------+
        | span of 1     | span of 1     | span of 1    |
        +---------------+---------------+--------------+
        |    This cell with a span of 3 is centered    |
        +---------------+---------------+--------------+
    */

    let mut table: prettytable::Table = table![
    [H2 -> "This is a cell with span of 2", "span of 1"],
    ["span of 1", "span of 1", "span of 1"],
    [H03c -> "This cell with a span of 3 is centered"]
    ];
    table.set_titles(Row::new(vec![Cell::new_align(
        "A table with horizontal span",
        Alignment::CENTER,
    )
    .with_hspan(3)]));
    table.printstd();
}
examples/style.rs (line 32)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn main() {
    let _ = table!();
    let mut table = Table::new();
    // Add style to a cell
    table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
    // Add style to a full row
    table.add_row(row![FY => "styled", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        // Create a cell with a red foreground color
        Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
        // Create a cell with red foreground color, yellow background color, with bold characters
        Cell::new("foo2").style_spec("FrByb"),
        // Using the cell! macro
        cell!(Fr->"red"),
    ]));

    table.printstd();

    // Print a table with some styles on it :
    // FrBybl means : Foregound red, Background yellow, bold, left align
    ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);

    // You can also apply style to full rows :
    let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
    // Set a title line, with all text centered in the cell
    table.set_titles(row![c => "Title 1", "Title 2"]);
    table.printstd();
}
examples/formatting.rs (line 5)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
fn main() {
    let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
    table.set_titles(row!["Title 1", "Title 2"]);

    // Print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // +-------------+------------+
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("FORMAT_NO_LINESEP_WITH_TITLE :");
    table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
    table.printstd();
    println!("");

    // Print
    // -------------------------
    //  Title 1      Title 2
    // =========================
    //  Value 1      Value 2
    // -------------------------
    //  Value three  Value four
    // -------------------------
    println!("FORMAT_NO_COLSEP :");
    table.set_format(*format::consts::FORMAT_NO_COLSEP);
    table.printstd();
    println!("");

    // Print
    // +-------------------------+
    // | Title 1      Title 2    |
    // +=========================+
    // | Value 1      Value 2    |
    // | Value three  Value four |
    // +-------------------------+
    println!("FORMAT_BORDERS_ONLY :");
    table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
    table.printstd();
    println!("");

    // Custom format can be implemented using `prettytable::format::FormatBuilder`
    // Example to print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("Custom :");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('|')
            .borders('|')
            .separators(
                &[format::LinePosition::Top, format::LinePosition::Bottom],
                format::LineSeparator::new('-', '+', '+', '+'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode
    // Example to print
    // ┌─────────────┬────────────┐
    // │ Title 1     │ Title 2    │
    // ├─────────────┼────────────┤
    // │ Value 1     │ Value 2    │
    // ├─────────────┼────────────┤
    // │ Value three │ Value four │
    // └─────────────┴────────────┘
    println!("With unicode:");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('│')
            .borders('│')
            .separators(
                &[format::LinePosition::Top],
                format::LineSeparator::new('─', '┬', '┌', '┐'),
            )
            .separators(
                &[format::LinePosition::Intern],
                format::LineSeparator::new('─', '┼', '├', '┤'),
            )
            .separators(
                &[format::LinePosition::Bottom],
                format::LineSeparator::new('─', '┴', '└', '┘'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode and different padding
    // Example to print
    // ┌───────────────┬──────────────┐
    // │  Title 1      │  Title 2     │
    // ├───────────────┼──────────────┤
    // │  Value 1      │  Value 2     │
    // ├───────────────┼──────────────┤
    // │  Value three  │  Value four  │
    // └───────────────┴──────────────┘
    // Change individual format settings
    println!("With unicode and padding:");
    table.get_format().padding(2, 2);
    table.printstd();
}

Unset the title line

Get a mutable reference to a row

Examples found in repository?
examples/tictactoe.rs (line 44)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
fn main() {
    let mut table = table![
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY]
    ];
    let mut height = table.print_tty(false).unwrap();
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    let mut current = CROSS;
    let mut terminal = term::stdout().unwrap();
    loop {
        let mut line = String::new();
        print!("{} plays > ", current);
        height += 1;
        stdout.flush().unwrap();
        stdin.read_line(&mut line).expect("Cannot read input");
        let i = match usize::from_str(line.trim()) {
            Ok(i) => i,
            _ => {
                println!("Bad input");
                height += 1;
                continue;
            }
        };
        if i < 1 || i > 9 {
            println!("Bad input, should be between 1 and 9");
            height += 1;
            continue;
        }
        let x = (i - 1) % 3;
        let y = (i - 1) / 3;
        {
            let row = table.get_mut_row(y).unwrap();
            if row.get_cell(x).unwrap().to_string() != EMPTY {
                println!("There's already someone there");
                height += 1;
                continue;
            }
            row.set_cell(cell!(current), x).unwrap();
        }
        for _ in 0..height {
            terminal.cursor_up().unwrap();
            terminal.delete_line().unwrap();
        }
        height = table.print_tty(false).unwrap();
        if check(&table) {
            return;
        }
        if current == CROSS {
            current = ROUND;
        } else {
            current = CROSS;
        }
    }
}

Get an immutable reference to a row

Examples found in repository?
examples/tictactoe.rs (line 69)
68
69
70
71
72
73
74
75
76
fn get(table: &Table, x: usize, y: usize) -> String {
    match table.get_row(y) {
        Some(r) => match r.get_cell(x) {
            Some(c) => c.to_string(),
            _ => EMPTY.to_string(),
        },
        _ => EMPTY.to_string(),
    }
}

Append a row in the table, transferring ownership of this row to the table and returning a mutable reference to the row

Examples found in repository?
examples/basic.rs (line 23)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let mut table = Table::new();
    table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
    table.add_row(row!["foobar", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        Cell::new("bar2"),
        Cell::new("foo2"),
    ]));
    table.printstd();
    println!("Modified : ");
    table.set_element("new_foo", 2, 1).unwrap();
    table.printstd();

    // The same table can be built the following way :
    let _table = table!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );

    // Or directly print it like this
    let _table = ptable!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );
}
More examples
Hide additional examples
examples/style.rs (line 10)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn main() {
    let _ = table!();
    let mut table = Table::new();
    // Add style to a cell
    table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
    // Add style to a full row
    table.add_row(row![FY => "styled", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        // Create a cell with a red foreground color
        Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
        // Create a cell with red foreground color, yellow background color, with bold characters
        Cell::new("foo2").style_spec("FrByb"),
        // Using the cell! macro
        cell!(Fr->"red"),
    ]));

    table.printstd();

    // Print a table with some styles on it :
    // FrBybl means : Foregound red, Background yellow, bold, left align
    ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);

    // You can also apply style to full rows :
    let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
    // Set a title line, with all text centered in the cell
    table.set_titles(row![c => "Title 1", "Title 2"]);
    table.printstd();
}

Append an empty row in the table. Return a mutable reference to this new row.

Insert row at the position index, and return a mutable reference to this row. If index is higher than current numbers of rows, row is appended at the end of the table

Modify a single element in the table

Examples found in repository?
examples/basic.rs (line 32)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let mut table = Table::new();
    table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
    table.add_row(row!["foobar", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        Cell::new("bar2"),
        Cell::new("foo2"),
    ]));
    table.printstd();
    println!("Modified : ");
    table.set_element("new_foo", 2, 1).unwrap();
    table.printstd();

    // The same table can be built the following way :
    let _table = table!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );

    // Or directly print it like this
    let _table = ptable!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );
}

Remove the row at position index. Silently skip if the row does not exist

Return an iterator over the immutable cells of the column specified by column

Return an iterator over the mutable cells of the column specified by column

Returns an iterator over immutable rows

Returns an iterator over mutable rows

Print the table to out and returns the number of lines printed, or an error

Print the table to terminal out, applying styles when needed and returns the number of lines printed, or an error

Print the table to standard output. Colors won’t be displayed unless stdout is a tty terminal, or force_colorize is set to true. In ANSI terminals, colors are displayed using ANSI escape characters. When for example the output is redirected to a file, or piped to another program, the output is considered as not beeing tty, and ANSI escape characters won’t be displayed unless force colorize is set to true.

Returns

A Result holding the number of lines printed, or an io::Error if any failure happens

Examples found in repository?
examples/tictactoe.rs (line 17)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
fn main() {
    let mut table = table![
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY]
    ];
    let mut height = table.print_tty(false).unwrap();
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    let mut current = CROSS;
    let mut terminal = term::stdout().unwrap();
    loop {
        let mut line = String::new();
        print!("{} plays > ", current);
        height += 1;
        stdout.flush().unwrap();
        stdin.read_line(&mut line).expect("Cannot read input");
        let i = match usize::from_str(line.trim()) {
            Ok(i) => i,
            _ => {
                println!("Bad input");
                height += 1;
                continue;
            }
        };
        if i < 1 || i > 9 {
            println!("Bad input, should be between 1 and 9");
            height += 1;
            continue;
        }
        let x = (i - 1) % 3;
        let y = (i - 1) / 3;
        {
            let row = table.get_mut_row(y).unwrap();
            if row.get_cell(x).unwrap().to_string() != EMPTY {
                println!("There's already someone there");
                height += 1;
                continue;
            }
            row.set_cell(cell!(current), x).unwrap();
        }
        for _ in 0..height {
            terminal.cursor_up().unwrap();
            terminal.delete_line().unwrap();
        }
        height = table.print_tty(false).unwrap();
        if check(&table) {
            return;
        }
        if current == CROSS {
            current = ROUND;
        } else {
            current = CROSS;
        }
    }
}

Print the table to standard output. Colors won’t be displayed unless stdout is a tty terminal. This means that if stdout is redirected to a file, or piped to another program, no color will be displayed. To force colors rendering, use print_tty() method. Any failure to print is ignored. For better control, use print_tty(). Calling printstd() is equivalent to calling print_tty(false) and ignoring the result.

Examples found in repository?
examples/multiline.rs (line 31)
20
21
22
23
24
25
26
27
28
29
30
31
32
fn main() {
    let table1 = table!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );
    let table2 = table!(
        ["Title 1", "Title 2"],
        ["This is\na multiline\ncell", "foo"],
        ["Yo dawg ;) You can even\nprint tables\ninto tables", table1]
    );
    table2.printstd();
}
More examples
Hide additional examples
examples/csv.rs (line 25)
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
fn main() {
    use prettytable::Table;

    let table = Table::from_csv_string(
        "ABC,DEFG,HIJKLMN\n\
                                        foobar,bar,foo\n\
                                        foobar2,bar2,foo2",
    )
    .unwrap();
    table.printstd();

    println!("");
    println!(
        "{}",
        String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
    );
}
examples/basic.rs (line 30)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn main() {
    let mut table = Table::new();
    table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
    table.add_row(row!["foobar", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        Cell::new("bar2"),
        Cell::new("foo2"),
    ]));
    table.printstd();
    println!("Modified : ");
    table.set_element("new_foo", 2, 1).unwrap();
    table.printstd();

    // The same table can be built the following way :
    let _table = table!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );

    // Or directly print it like this
    let _table = ptable!(
        ["ABC", "DEFG", "HIJKLMN"],
        ["foobar", "bar", "foo"],
        ["foobar2", "bar2", "foo2"]
    );
}
examples/span.rs (line 28)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
    /*
        The following code will output

        +---------------+---------------+--------------+
        |         A table with horizontal span         |
        +===============+===============+==============+
        | This is a cell with span of 2 | span of 1    |
        +---------------+---------------+--------------+
        | span of 1     | span of 1     | span of 1    |
        +---------------+---------------+--------------+
        |    This cell with a span of 3 is centered    |
        +---------------+---------------+--------------+
    */

    let mut table: prettytable::Table = table![
    [H2 -> "This is a cell with span of 2", "span of 1"],
    ["span of 1", "span of 1", "span of 1"],
    [H03c -> "This cell with a span of 3 is centered"]
    ];
    table.set_titles(Row::new(vec![Cell::new_align(
        "A table with horizontal span",
        Alignment::CENTER,
    )
    .with_hspan(3)]));
    table.printstd();
}
examples/style.rs (line 23)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn main() {
    let _ = table!();
    let mut table = Table::new();
    // Add style to a cell
    table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
    // Add style to a full row
    table.add_row(row![FY => "styled", "bar", "foo"]);
    table.add_row(Row::new(vec![
        Cell::new("foobar2"),
        // Create a cell with a red foreground color
        Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
        // Create a cell with red foreground color, yellow background color, with bold characters
        Cell::new("foo2").style_spec("FrByb"),
        // Using the cell! macro
        cell!(Fr->"red"),
    ]));

    table.printstd();

    // Print a table with some styles on it :
    // FrBybl means : Foregound red, Background yellow, bold, left align
    ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);

    // You can also apply style to full rows :
    let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
    // Set a title line, with all text centered in the cell
    table.set_titles(row![c => "Title 1", "Title 2"]);
    table.printstd();
}
examples/formatting.rs (line 16)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
fn main() {
    let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
    table.set_titles(row!["Title 1", "Title 2"]);

    // Print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // +-------------+------------+
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("FORMAT_NO_LINESEP_WITH_TITLE :");
    table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
    table.printstd();
    println!("");

    // Print
    // -------------------------
    //  Title 1      Title 2
    // =========================
    //  Value 1      Value 2
    // -------------------------
    //  Value three  Value four
    // -------------------------
    println!("FORMAT_NO_COLSEP :");
    table.set_format(*format::consts::FORMAT_NO_COLSEP);
    table.printstd();
    println!("");

    // Print
    // +-------------------------+
    // | Title 1      Title 2    |
    // +=========================+
    // | Value 1      Value 2    |
    // | Value three  Value four |
    // +-------------------------+
    println!("FORMAT_BORDERS_ONLY :");
    table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
    table.printstd();
    println!("");

    // Custom format can be implemented using `prettytable::format::FormatBuilder`
    // Example to print
    // +-------------+------------+
    // | Title 1     | Title 2    |
    // | Value 1     | Value 2    |
    // | Value three | Value four |
    // +-------------+------------+
    println!("Custom :");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('|')
            .borders('|')
            .separators(
                &[format::LinePosition::Top, format::LinePosition::Bottom],
                format::LineSeparator::new('-', '+', '+', '+'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode
    // Example to print
    // ┌─────────────┬────────────┐
    // │ Title 1     │ Title 2    │
    // ├─────────────┼────────────┤
    // │ Value 1     │ Value 2    │
    // ├─────────────┼────────────┤
    // │ Value three │ Value four │
    // └─────────────┴────────────┘
    println!("With unicode:");
    table.set_format(
        format::FormatBuilder::new()
            .column_separator('│')
            .borders('│')
            .separators(
                &[format::LinePosition::Top],
                format::LineSeparator::new('─', '┬', '┌', '┐'),
            )
            .separators(
                &[format::LinePosition::Intern],
                format::LineSeparator::new('─', '┼', '├', '┤'),
            )
            .separators(
                &[format::LinePosition::Bottom],
                format::LineSeparator::new('─', '┴', '└', '┘'),
            )
            .padding(1, 1)
            .build(),
    );
    table.printstd();

    // Customized format with unicode and different padding
    // Example to print
    // ┌───────────────┬──────────────┐
    // │  Title 1      │  Title 2     │
    // ├───────────────┼──────────────┤
    // │  Value 1      │  Value 2     │
    // ├───────────────┼──────────────┤
    // │  Value three  │  Value four  │
    // └───────────────┴──────────────┘
    // Change individual format settings
    println!("With unicode and padding:");
    table.get_format().padding(2, 2);
    table.printstd();
}

Print table in HTML format to out.

Trait Implementations§

Get a slice from self
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Converts to this type from the input type.
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more
Performs the mutable indexing (container[index]) operation. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

Type output after slicing
Get a slice from self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.