pub struct Table { /* private fields */ }
Expand description
An owned printable table
Implementations§
Source§impl Table
impl Table
Sourcepub fn from_csv_string(csv_s: &str) -> Result<Self>
pub fn from_csv_string(csv_s: &str) -> Result<Self>
Create a table from a CSV string
For more customisability use from_csv()
Examples found in repository?
16fn main() {
17 use prettytable::Table;
18
19 let table = Table::from_csv_string(
20 "ABC,DEFG,HIJKLMN\n\
21 foobar,bar,foo\n\
22 foobar2,bar2,foo2",
23 )
24 .unwrap();
25 table.printstd();
26
27 println!("");
28 println!(
29 "{}",
30 String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
31 );
32}
Sourcepub fn from_csv_file<P: AsRef<Path>>(csv_p: P) -> Result<Self>
pub fn from_csv_file<P: AsRef<Path>>(csv_p: P) -> Result<Self>
Create a table from a CSV file
For more customisability use from_csv()
Sourcepub fn to_csv<W: Write>(&self, w: W) -> Result<Writer<W>>
pub fn to_csv<W: Write>(&self, w: W) -> Result<Writer<W>>
Write the table to the specified writer.
Examples found in repository?
16fn main() {
17 use prettytable::Table;
18
19 let table = Table::from_csv_string(
20 "ABC,DEFG,HIJKLMN\n\
21 foobar,bar,foo\n\
22 foobar2,bar2,foo2",
23 )
24 .unwrap();
25 table.printstd();
26
27 println!("");
28 println!(
29 "{}",
30 String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
31 );
32}
Source§impl Table
impl Table
Sourcepub fn new() -> Table
pub fn new() -> Table
Create an empty table
Examples found in repository?
21fn main() {
22 let mut table = Table::new();
23 table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
24 table.add_row(row!["foobar", "bar", "foo"]);
25 table.add_row(Row::new(vec![
26 Cell::new("foobar2"),
27 Cell::new("bar2"),
28 Cell::new("foo2"),
29 ]));
30 table.printstd();
31 println!("Modified : ");
32 table.set_element("new_foo", 2, 1).unwrap();
33 table.printstd();
34
35 // The same table can be built the following way :
36 let _table = table!(
37 ["ABC", "DEFG", "HIJKLMN"],
38 ["foobar", "bar", "foo"],
39 ["foobar2", "bar2", "foo2"]
40 );
41
42 // Or directly print it like this
43 let _table = ptable!(
44 ["ABC", "DEFG", "HIJKLMN"],
45 ["foobar", "bar", "foo"],
46 ["foobar2", "bar2", "foo2"]
47 );
48}
More examples
6fn main() {
7 let _ = table!();
8 let mut table = Table::new();
9 // Add style to a cell
10 table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
11 // Add style to a full row
12 table.add_row(row![FY => "styled", "bar", "foo"]);
13 table.add_row(Row::new(vec![
14 Cell::new("foobar2"),
15 // Create a cell with a red foreground color
16 Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
17 // Create a cell with red foreground color, yellow background color, with bold characters
18 Cell::new("foo2").style_spec("FrByb"),
19 // Using the cell! macro
20 cell!(Fr->"red"),
21 ]));
22
23 table.printstd();
24
25 // Print a table with some styles on it :
26 // FrBybl means : Foregound red, Background yellow, bold, left align
27 ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
28
29 // You can also apply style to full rows :
30 let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
31 // Set a title line, with all text centered in the cell
32 table.set_titles(row![c => "Title 1", "Title 2"]);
33 table.printstd();
34}
Sourcepub fn set_format(&mut self, format: TableFormat)
pub fn set_format(&mut self, format: TableFormat)
Change the table format. Eg : Separators
Examples found in repository?
3fn main() {
4 let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
5 table.set_titles(row!["Title 1", "Title 2"]);
6
7 // Print
8 // +-------------+------------+
9 // | Title 1 | Title 2 |
10 // +-------------+------------+
11 // | Value 1 | Value 2 |
12 // | Value three | Value four |
13 // +-------------+------------+
14 println!("FORMAT_NO_LINESEP_WITH_TITLE :");
15 table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
16 table.printstd();
17 println!("");
18
19 // Print
20 // -------------------------
21 // Title 1 Title 2
22 // =========================
23 // Value 1 Value 2
24 // -------------------------
25 // Value three Value four
26 // -------------------------
27 println!("FORMAT_NO_COLSEP :");
28 table.set_format(*format::consts::FORMAT_NO_COLSEP);
29 table.printstd();
30 println!("");
31
32 // Print
33 // +-------------------------+
34 // | Title 1 Title 2 |
35 // +=========================+
36 // | Value 1 Value 2 |
37 // | Value three Value four |
38 // +-------------------------+
39 println!("FORMAT_BORDERS_ONLY :");
40 table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
41 table.printstd();
42 println!("");
43
44 // Custom format can be implemented using `prettytable::format::FormatBuilder`
45 // Example to print
46 // +-------------+------------+
47 // | Title 1 | Title 2 |
48 // | Value 1 | Value 2 |
49 // | Value three | Value four |
50 // +-------------+------------+
51 println!("Custom :");
52 table.set_format(
53 format::FormatBuilder::new()
54 .column_separator('|')
55 .borders('|')
56 .separators(
57 &[format::LinePosition::Top, format::LinePosition::Bottom],
58 format::LineSeparator::new('-', '+', '+', '+'),
59 )
60 .padding(1, 1)
61 .build(),
62 );
63 table.printstd();
64
65 // Customized format with unicode
66 // Example to print
67 // ┌─────────────┬────────────┐
68 // │ Title 1 │ Title 2 │
69 // ├─────────────┼────────────┤
70 // │ Value 1 │ Value 2 │
71 // ├─────────────┼────────────┤
72 // │ Value three │ Value four │
73 // └─────────────┴────────────┘
74 println!("With unicode:");
75 table.set_format(
76 format::FormatBuilder::new()
77 .column_separator('│')
78 .borders('│')
79 .separators(
80 &[format::LinePosition::Top],
81 format::LineSeparator::new('─', '┬', '┌', '┐'),
82 )
83 .separators(
84 &[format::LinePosition::Intern],
85 format::LineSeparator::new('─', '┼', '├', '┤'),
86 )
87 .separators(
88 &[format::LinePosition::Bottom],
89 format::LineSeparator::new('─', '┴', '└', '┘'),
90 )
91 .padding(1, 1)
92 .build(),
93 );
94 table.printstd();
95
96 // Customized format with unicode and different padding
97 // Example to print
98 // ┌───────────────┬──────────────┐
99 // │ Title 1 │ Title 2 │
100 // ├───────────────┼──────────────┤
101 // │ Value 1 │ Value 2 │
102 // ├───────────────┼──────────────┤
103 // │ Value three │ Value four │
104 // └───────────────┴──────────────┘
105 // Change individual format settings
106 println!("With unicode and padding:");
107 table.get_format().padding(2, 2);
108 table.printstd();
109}
Sourcepub fn get_format(&mut self) -> &mut TableFormat
pub fn get_format(&mut self) -> &mut TableFormat
Get a mutable reference to the internal format
Examples found in repository?
3fn main() {
4 let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
5 table.set_titles(row!["Title 1", "Title 2"]);
6
7 // Print
8 // +-------------+------------+
9 // | Title 1 | Title 2 |
10 // +-------------+------------+
11 // | Value 1 | Value 2 |
12 // | Value three | Value four |
13 // +-------------+------------+
14 println!("FORMAT_NO_LINESEP_WITH_TITLE :");
15 table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
16 table.printstd();
17 println!("");
18
19 // Print
20 // -------------------------
21 // Title 1 Title 2
22 // =========================
23 // Value 1 Value 2
24 // -------------------------
25 // Value three Value four
26 // -------------------------
27 println!("FORMAT_NO_COLSEP :");
28 table.set_format(*format::consts::FORMAT_NO_COLSEP);
29 table.printstd();
30 println!("");
31
32 // Print
33 // +-------------------------+
34 // | Title 1 Title 2 |
35 // +=========================+
36 // | Value 1 Value 2 |
37 // | Value three Value four |
38 // +-------------------------+
39 println!("FORMAT_BORDERS_ONLY :");
40 table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
41 table.printstd();
42 println!("");
43
44 // Custom format can be implemented using `prettytable::format::FormatBuilder`
45 // Example to print
46 // +-------------+------------+
47 // | Title 1 | Title 2 |
48 // | Value 1 | Value 2 |
49 // | Value three | Value four |
50 // +-------------+------------+
51 println!("Custom :");
52 table.set_format(
53 format::FormatBuilder::new()
54 .column_separator('|')
55 .borders('|')
56 .separators(
57 &[format::LinePosition::Top, format::LinePosition::Bottom],
58 format::LineSeparator::new('-', '+', '+', '+'),
59 )
60 .padding(1, 1)
61 .build(),
62 );
63 table.printstd();
64
65 // Customized format with unicode
66 // Example to print
67 // ┌─────────────┬────────────┐
68 // │ Title 1 │ Title 2 │
69 // ├─────────────┼────────────┤
70 // │ Value 1 │ Value 2 │
71 // ├─────────────┼────────────┤
72 // │ Value three │ Value four │
73 // └─────────────┴────────────┘
74 println!("With unicode:");
75 table.set_format(
76 format::FormatBuilder::new()
77 .column_separator('│')
78 .borders('│')
79 .separators(
80 &[format::LinePosition::Top],
81 format::LineSeparator::new('─', '┬', '┌', '┐'),
82 )
83 .separators(
84 &[format::LinePosition::Intern],
85 format::LineSeparator::new('─', '┼', '├', '┤'),
86 )
87 .separators(
88 &[format::LinePosition::Bottom],
89 format::LineSeparator::new('─', '┴', '└', '┘'),
90 )
91 .padding(1, 1)
92 .build(),
93 );
94 table.printstd();
95
96 // Customized format with unicode and different padding
97 // Example to print
98 // ┌───────────────┬──────────────┐
99 // │ Title 1 │ Title 2 │
100 // ├───────────────┼──────────────┤
101 // │ Value 1 │ Value 2 │
102 // ├───────────────┼──────────────┤
103 // │ Value three │ Value four │
104 // └───────────────┴──────────────┘
105 // Change individual format settings
106 println!("With unicode and padding:");
107 table.get_format().padding(2, 2);
108 table.printstd();
109}
Sourcepub fn set_titles(&mut self, titles: Row)
pub fn set_titles(&mut self, titles: Row)
Set the optional title lines
Examples found in repository?
3fn main() {
4 let mut table = table![
5 [0, 0, 0],
6 [1, 1, 1],
7 [2, 2, 2],
8 [3, 3, 3],
9 [4, 4, 4],
10 [5, 5, 5]
11 ];
12 table.set_titles(row!["t1", "t2", "t3"]);
13
14 let slice = table.slice(..);
15 let slice = slice.slice(2..);
16 let slice = slice.slice(..3);
17
18 /*
19 Will print
20 +----+----+----+
21 | t1 | t2 | t3 |
22 +====+====+====+
23 | 2 | 2 | 2 |
24 +----+----+----+
25 | 3 | 3 | 3 |
26 +----+----+----+
27 | 4 | 4 | 4 |
28 +----+----+----+
29 */
30 slice.printstd();
31
32 // This is equivalent to
33 let slice = table.slice(2..5);
34 slice.printstd();
35}
More examples
3fn main() {
4 /*
5 The following code will output
6
7 +---------------+---------------+--------------+
8 | A table with horizontal span |
9 +===============+===============+==============+
10 | This is a cell with span of 2 | span of 1 |
11 +---------------+---------------+--------------+
12 | span of 1 | span of 1 | span of 1 |
13 +---------------+---------------+--------------+
14 | This cell with a span of 3 is centered |
15 +---------------+---------------+--------------+
16 */
17
18 let mut table: prettytable::Table = table![
19 [H2 -> "This is a cell with span of 2", "span of 1"],
20 ["span of 1", "span of 1", "span of 1"],
21 [H03c -> "This cell with a span of 3 is centered"]
22 ];
23 table.set_titles(Row::new(vec![Cell::new_align(
24 "A table with horizontal span",
25 Alignment::CENTER,
26 )
27 .with_hspan(3)]));
28 table.printstd();
29}
6fn main() {
7 let _ = table!();
8 let mut table = Table::new();
9 // Add style to a cell
10 table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
11 // Add style to a full row
12 table.add_row(row![FY => "styled", "bar", "foo"]);
13 table.add_row(Row::new(vec![
14 Cell::new("foobar2"),
15 // Create a cell with a red foreground color
16 Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
17 // Create a cell with red foreground color, yellow background color, with bold characters
18 Cell::new("foo2").style_spec("FrByb"),
19 // Using the cell! macro
20 cell!(Fr->"red"),
21 ]));
22
23 table.printstd();
24
25 // Print a table with some styles on it :
26 // FrBybl means : Foregound red, Background yellow, bold, left align
27 ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
28
29 // You can also apply style to full rows :
30 let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
31 // Set a title line, with all text centered in the cell
32 table.set_titles(row![c => "Title 1", "Title 2"]);
33 table.printstd();
34}
3fn main() {
4 let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
5 table.set_titles(row!["Title 1", "Title 2"]);
6
7 // Print
8 // +-------------+------------+
9 // | Title 1 | Title 2 |
10 // +-------------+------------+
11 // | Value 1 | Value 2 |
12 // | Value three | Value four |
13 // +-------------+------------+
14 println!("FORMAT_NO_LINESEP_WITH_TITLE :");
15 table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
16 table.printstd();
17 println!("");
18
19 // Print
20 // -------------------------
21 // Title 1 Title 2
22 // =========================
23 // Value 1 Value 2
24 // -------------------------
25 // Value three Value four
26 // -------------------------
27 println!("FORMAT_NO_COLSEP :");
28 table.set_format(*format::consts::FORMAT_NO_COLSEP);
29 table.printstd();
30 println!("");
31
32 // Print
33 // +-------------------------+
34 // | Title 1 Title 2 |
35 // +=========================+
36 // | Value 1 Value 2 |
37 // | Value three Value four |
38 // +-------------------------+
39 println!("FORMAT_BORDERS_ONLY :");
40 table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
41 table.printstd();
42 println!("");
43
44 // Custom format can be implemented using `prettytable::format::FormatBuilder`
45 // Example to print
46 // +-------------+------------+
47 // | Title 1 | Title 2 |
48 // | Value 1 | Value 2 |
49 // | Value three | Value four |
50 // +-------------+------------+
51 println!("Custom :");
52 table.set_format(
53 format::FormatBuilder::new()
54 .column_separator('|')
55 .borders('|')
56 .separators(
57 &[format::LinePosition::Top, format::LinePosition::Bottom],
58 format::LineSeparator::new('-', '+', '+', '+'),
59 )
60 .padding(1, 1)
61 .build(),
62 );
63 table.printstd();
64
65 // Customized format with unicode
66 // Example to print
67 // ┌─────────────┬────────────┐
68 // │ Title 1 │ Title 2 │
69 // ├─────────────┼────────────┤
70 // │ Value 1 │ Value 2 │
71 // ├─────────────┼────────────┤
72 // │ Value three │ Value four │
73 // └─────────────┴────────────┘
74 println!("With unicode:");
75 table.set_format(
76 format::FormatBuilder::new()
77 .column_separator('│')
78 .borders('│')
79 .separators(
80 &[format::LinePosition::Top],
81 format::LineSeparator::new('─', '┬', '┌', '┐'),
82 )
83 .separators(
84 &[format::LinePosition::Intern],
85 format::LineSeparator::new('─', '┼', '├', '┤'),
86 )
87 .separators(
88 &[format::LinePosition::Bottom],
89 format::LineSeparator::new('─', '┴', '└', '┘'),
90 )
91 .padding(1, 1)
92 .build(),
93 );
94 table.printstd();
95
96 // Customized format with unicode and different padding
97 // Example to print
98 // ┌───────────────┬──────────────┐
99 // │ Title 1 │ Title 2 │
100 // ├───────────────┼──────────────┤
101 // │ Value 1 │ Value 2 │
102 // ├───────────────┼──────────────┤
103 // │ Value three │ Value four │
104 // └───────────────┴──────────────┘
105 // Change individual format settings
106 println!("With unicode and padding:");
107 table.get_format().padding(2, 2);
108 table.printstd();
109}
Sourcepub fn unset_titles(&mut self)
pub fn unset_titles(&mut self)
Unset the title line
Sourcepub fn get_mut_row(&mut self, row: usize) -> Option<&mut Row>
pub fn get_mut_row(&mut self, row: usize) -> Option<&mut Row>
Get a mutable reference to a row
Examples found in repository?
11fn main() {
12 let mut table = table![
13 [EMPTY, EMPTY, EMPTY],
14 [EMPTY, EMPTY, EMPTY],
15 [EMPTY, EMPTY, EMPTY]
16 ];
17 let mut height = table.print_tty(false).unwrap();
18 let stdin = io::stdin();
19 let mut stdout = io::stdout();
20 let mut current = CROSS;
21 let mut terminal = term::stdout().unwrap();
22 loop {
23 let mut line = String::new();
24 print!("{} plays > ", current);
25 height += 1;
26 stdout.flush().unwrap();
27 stdin.read_line(&mut line).expect("Cannot read input");
28 let i = match usize::from_str(line.trim()) {
29 Ok(i) => i,
30 _ => {
31 println!("Bad input");
32 height += 1;
33 continue;
34 }
35 };
36 if i < 1 || i > 9 {
37 println!("Bad input, should be between 1 and 9");
38 height += 1;
39 continue;
40 }
41 let x = (i - 1) % 3;
42 let y = (i - 1) / 3;
43 {
44 let row = table.get_mut_row(y).unwrap();
45 if row.get_cell(x).unwrap().to_string() != EMPTY {
46 println!("There's already someone there");
47 height += 1;
48 continue;
49 }
50 row.set_cell(cell!(current), x).unwrap();
51 }
52 for _ in 0..height {
53 terminal.cursor_up().unwrap();
54 terminal.delete_line().unwrap();
55 }
56 height = table.print_tty(false).unwrap();
57 if check(&table) {
58 return;
59 }
60 if current == CROSS {
61 current = ROUND;
62 } else {
63 current = CROSS;
64 }
65 }
66}
Sourcepub fn add_row(&mut self, row: Row) -> &mut Row
pub fn add_row(&mut self, row: Row) -> &mut Row
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?
21fn main() {
22 let mut table = Table::new();
23 table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
24 table.add_row(row!["foobar", "bar", "foo"]);
25 table.add_row(Row::new(vec![
26 Cell::new("foobar2"),
27 Cell::new("bar2"),
28 Cell::new("foo2"),
29 ]));
30 table.printstd();
31 println!("Modified : ");
32 table.set_element("new_foo", 2, 1).unwrap();
33 table.printstd();
34
35 // The same table can be built the following way :
36 let _table = table!(
37 ["ABC", "DEFG", "HIJKLMN"],
38 ["foobar", "bar", "foo"],
39 ["foobar2", "bar2", "foo2"]
40 );
41
42 // Or directly print it like this
43 let _table = ptable!(
44 ["ABC", "DEFG", "HIJKLMN"],
45 ["foobar", "bar", "foo"],
46 ["foobar2", "bar2", "foo2"]
47 );
48}
More examples
6fn main() {
7 let _ = table!();
8 let mut table = Table::new();
9 // Add style to a cell
10 table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
11 // Add style to a full row
12 table.add_row(row![FY => "styled", "bar", "foo"]);
13 table.add_row(Row::new(vec![
14 Cell::new("foobar2"),
15 // Create a cell with a red foreground color
16 Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
17 // Create a cell with red foreground color, yellow background color, with bold characters
18 Cell::new("foo2").style_spec("FrByb"),
19 // Using the cell! macro
20 cell!(Fr->"red"),
21 ]));
22
23 table.printstd();
24
25 // Print a table with some styles on it :
26 // FrBybl means : Foregound red, Background yellow, bold, left align
27 ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
28
29 // You can also apply style to full rows :
30 let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
31 // Set a title line, with all text centered in the cell
32 table.set_titles(row![c => "Title 1", "Title 2"]);
33 table.printstd();
34}
Sourcepub fn add_empty_row(&mut self) -> &mut Row
pub fn add_empty_row(&mut self) -> &mut Row
Append an empty row in the table. Return a mutable reference to this new row.
Sourcepub fn insert_row(&mut self, index: usize, row: Row) -> &mut Row
pub fn insert_row(&mut self, index: usize, row: Row) -> &mut 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
Sourcepub fn set_element(
&mut self,
element: &str,
column: usize,
row: usize,
) -> Result<(), &str>
pub fn set_element( &mut self, element: &str, column: usize, row: usize, ) -> Result<(), &str>
Modify a single element in the table
Examples found in repository?
21fn main() {
22 let mut table = Table::new();
23 table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
24 table.add_row(row!["foobar", "bar", "foo"]);
25 table.add_row(Row::new(vec![
26 Cell::new("foobar2"),
27 Cell::new("bar2"),
28 Cell::new("foo2"),
29 ]));
30 table.printstd();
31 println!("Modified : ");
32 table.set_element("new_foo", 2, 1).unwrap();
33 table.printstd();
34
35 // The same table can be built the following way :
36 let _table = table!(
37 ["ABC", "DEFG", "HIJKLMN"],
38 ["foobar", "bar", "foo"],
39 ["foobar2", "bar2", "foo2"]
40 );
41
42 // Or directly print it like this
43 let _table = ptable!(
44 ["ABC", "DEFG", "HIJKLMN"],
45 ["foobar", "bar", "foo"],
46 ["foobar2", "bar2", "foo2"]
47 );
48}
Sourcepub fn remove_row(&mut self, index: usize)
pub fn remove_row(&mut self, index: usize)
Remove the row at position index
. Silently skip if the row does not exist
Sourcepub fn column_iter(&self, column: usize) -> ColumnIter<'_> ⓘ
pub fn column_iter(&self, column: usize) -> ColumnIter<'_> ⓘ
Return an iterator over the immutable cells of the column specified by column
Sourcepub fn column_iter_mut(&mut self, column: usize) -> ColumnIterMut<'_> ⓘ
pub fn column_iter_mut(&mut self, column: usize) -> ColumnIterMut<'_> ⓘ
Return an iterator over the mutable cells of the column specified by column
Sourcepub fn row_iter_mut(&mut self) -> IterMut<'_, Row>
pub fn row_iter_mut(&mut self) -> IterMut<'_, Row>
Returns an iterator over mutable rows
Sourcepub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<usize, Error>
pub fn print<T: Write + ?Sized>(&self, out: &mut T) -> Result<usize, Error>
Print the table to out
and returns the number
of lines printed, or an error
Sourcepub fn print_term<T: Terminal + ?Sized>(
&self,
out: &mut T,
) -> Result<usize, Error>
pub fn print_term<T: Terminal + ?Sized>( &self, out: &mut T, ) -> Result<usize, Error>
Print the table to terminal out
, applying styles when needed and returns the number
of lines printed, or an error
Sourcepub fn print_tty(&self, force_colorize: bool) -> Result<usize, Error>
pub fn print_tty(&self, force_colorize: bool) -> Result<usize, 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?
11fn main() {
12 let mut table = table![
13 [EMPTY, EMPTY, EMPTY],
14 [EMPTY, EMPTY, EMPTY],
15 [EMPTY, EMPTY, EMPTY]
16 ];
17 let mut height = table.print_tty(false).unwrap();
18 let stdin = io::stdin();
19 let mut stdout = io::stdout();
20 let mut current = CROSS;
21 let mut terminal = term::stdout().unwrap();
22 loop {
23 let mut line = String::new();
24 print!("{} plays > ", current);
25 height += 1;
26 stdout.flush().unwrap();
27 stdin.read_line(&mut line).expect("Cannot read input");
28 let i = match usize::from_str(line.trim()) {
29 Ok(i) => i,
30 _ => {
31 println!("Bad input");
32 height += 1;
33 continue;
34 }
35 };
36 if i < 1 || i > 9 {
37 println!("Bad input, should be between 1 and 9");
38 height += 1;
39 continue;
40 }
41 let x = (i - 1) % 3;
42 let y = (i - 1) / 3;
43 {
44 let row = table.get_mut_row(y).unwrap();
45 if row.get_cell(x).unwrap().to_string() != EMPTY {
46 println!("There's already someone there");
47 height += 1;
48 continue;
49 }
50 row.set_cell(cell!(current), x).unwrap();
51 }
52 for _ in 0..height {
53 terminal.cursor_up().unwrap();
54 terminal.delete_line().unwrap();
55 }
56 height = table.print_tty(false).unwrap();
57 if check(&table) {
58 return;
59 }
60 if current == CROSS {
61 current = ROUND;
62 } else {
63 current = CROSS;
64 }
65 }
66}
Sourcepub fn printstd(&self)
pub fn printstd(&self)
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?
20fn main() {
21 let table1 = table!(
22 ["ABC", "DEFG", "HIJKLMN"],
23 ["foobar", "bar", "foo"],
24 ["foobar2", "bar2", "foo2"]
25 );
26 let table2 = table!(
27 ["Title 1", "Title 2"],
28 ["This is\na multiline\ncell", "foo"],
29 ["Yo dawg ;) You can even\nprint tables\ninto tables", table1]
30 );
31 table2.printstd();
32}
More examples
16fn main() {
17 use prettytable::Table;
18
19 let table = Table::from_csv_string(
20 "ABC,DEFG,HIJKLMN\n\
21 foobar,bar,foo\n\
22 foobar2,bar2,foo2",
23 )
24 .unwrap();
25 table.printstd();
26
27 println!("");
28 println!(
29 "{}",
30 String::from_utf8(table.to_csv(Vec::new()).unwrap().into_inner().unwrap()).unwrap()
31 );
32}
21fn main() {
22 let mut table = Table::new();
23 table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
24 table.add_row(row!["foobar", "bar", "foo"]);
25 table.add_row(Row::new(vec![
26 Cell::new("foobar2"),
27 Cell::new("bar2"),
28 Cell::new("foo2"),
29 ]));
30 table.printstd();
31 println!("Modified : ");
32 table.set_element("new_foo", 2, 1).unwrap();
33 table.printstd();
34
35 // The same table can be built the following way :
36 let _table = table!(
37 ["ABC", "DEFG", "HIJKLMN"],
38 ["foobar", "bar", "foo"],
39 ["foobar2", "bar2", "foo2"]
40 );
41
42 // Or directly print it like this
43 let _table = ptable!(
44 ["ABC", "DEFG", "HIJKLMN"],
45 ["foobar", "bar", "foo"],
46 ["foobar2", "bar2", "foo2"]
47 );
48}
3fn main() {
4 /*
5 The following code will output
6
7 +---------------+---------------+--------------+
8 | A table with horizontal span |
9 +===============+===============+==============+
10 | This is a cell with span of 2 | span of 1 |
11 +---------------+---------------+--------------+
12 | span of 1 | span of 1 | span of 1 |
13 +---------------+---------------+--------------+
14 | This cell with a span of 3 is centered |
15 +---------------+---------------+--------------+
16 */
17
18 let mut table: prettytable::Table = table![
19 [H2 -> "This is a cell with span of 2", "span of 1"],
20 ["span of 1", "span of 1", "span of 1"],
21 [H03c -> "This cell with a span of 3 is centered"]
22 ];
23 table.set_titles(Row::new(vec![Cell::new_align(
24 "A table with horizontal span",
25 Alignment::CENTER,
26 )
27 .with_hspan(3)]));
28 table.printstd();
29}
6fn main() {
7 let _ = table!();
8 let mut table = Table::new();
9 // Add style to a cell
10 table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
11 // Add style to a full row
12 table.add_row(row![FY => "styled", "bar", "foo"]);
13 table.add_row(Row::new(vec![
14 Cell::new("foobar2"),
15 // Create a cell with a red foreground color
16 Cell::new("bar2").with_style(Attr::ForegroundColor(color::RED)),
17 // Create a cell with red foreground color, yellow background color, with bold characters
18 Cell::new("foo2").style_spec("FrByb"),
19 // Using the cell! macro
20 cell!(Fr->"red"),
21 ]));
22
23 table.printstd();
24
25 // Print a table with some styles on it :
26 // FrBybl means : Foregound red, Background yellow, bold, left align
27 ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
28
29 // You can also apply style to full rows :
30 let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
31 // Set a title line, with all text centered in the cell
32 table.set_titles(row![c => "Title 1", "Title 2"]);
33 table.printstd();
34}
3fn main() {
4 let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
5 table.set_titles(row!["Title 1", "Title 2"]);
6
7 // Print
8 // +-------------+------------+
9 // | Title 1 | Title 2 |
10 // +-------------+------------+
11 // | Value 1 | Value 2 |
12 // | Value three | Value four |
13 // +-------------+------------+
14 println!("FORMAT_NO_LINESEP_WITH_TITLE :");
15 table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
16 table.printstd();
17 println!("");
18
19 // Print
20 // -------------------------
21 // Title 1 Title 2
22 // =========================
23 // Value 1 Value 2
24 // -------------------------
25 // Value three Value four
26 // -------------------------
27 println!("FORMAT_NO_COLSEP :");
28 table.set_format(*format::consts::FORMAT_NO_COLSEP);
29 table.printstd();
30 println!("");
31
32 // Print
33 // +-------------------------+
34 // | Title 1 Title 2 |
35 // +=========================+
36 // | Value 1 Value 2 |
37 // | Value three Value four |
38 // +-------------------------+
39 println!("FORMAT_BORDERS_ONLY :");
40 table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
41 table.printstd();
42 println!("");
43
44 // Custom format can be implemented using `prettytable::format::FormatBuilder`
45 // Example to print
46 // +-------------+------------+
47 // | Title 1 | Title 2 |
48 // | Value 1 | Value 2 |
49 // | Value three | Value four |
50 // +-------------+------------+
51 println!("Custom :");
52 table.set_format(
53 format::FormatBuilder::new()
54 .column_separator('|')
55 .borders('|')
56 .separators(
57 &[format::LinePosition::Top, format::LinePosition::Bottom],
58 format::LineSeparator::new('-', '+', '+', '+'),
59 )
60 .padding(1, 1)
61 .build(),
62 );
63 table.printstd();
64
65 // Customized format with unicode
66 // Example to print
67 // ┌─────────────┬────────────┐
68 // │ Title 1 │ Title 2 │
69 // ├─────────────┼────────────┤
70 // │ Value 1 │ Value 2 │
71 // ├─────────────┼────────────┤
72 // │ Value three │ Value four │
73 // └─────────────┴────────────┘
74 println!("With unicode:");
75 table.set_format(
76 format::FormatBuilder::new()
77 .column_separator('│')
78 .borders('│')
79 .separators(
80 &[format::LinePosition::Top],
81 format::LineSeparator::new('─', '┬', '┌', '┐'),
82 )
83 .separators(
84 &[format::LinePosition::Intern],
85 format::LineSeparator::new('─', '┼', '├', '┤'),
86 )
87 .separators(
88 &[format::LinePosition::Bottom],
89 format::LineSeparator::new('─', '┴', '└', '┘'),
90 )
91 .padding(1, 1)
92 .build(),
93 );
94 table.printstd();
95
96 // Customized format with unicode and different padding
97 // Example to print
98 // ┌───────────────┬──────────────┐
99 // │ Title 1 │ Title 2 │
100 // ├───────────────┼──────────────┤
101 // │ Value 1 │ Value 2 │
102 // ├───────────────┼──────────────┤
103 // │ Value three │ Value four │
104 // └───────────────┴──────────────┘
105 // Change individual format settings
106 println!("With unicode and padding:");
107 table.get_format().padding(2, 2);
108 table.printstd();
109}
Trait Implementations§
Source§impl AsTableSlice for Table
impl AsTableSlice for Table
Source§fn as_slice(&self) -> TableSlice<'_>
fn as_slice(&self) -> TableSlice<'_>
Source§impl<A: Into<Row>> Extend<A> for Table
impl<A: Into<Row>> Extend<A> for Table
Source§fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)