docx_rust/document/
table.rs

1#![allow(unused_must_use)]
2use hard_xml::{XmlRead, XmlWrite};
3use std::borrow::{Borrow, Cow};
4
5use crate::{
6    __setter, __xml_test_suites,
7    document::{TableGrid, TableRow},
8    formatting::TableProperty,
9};
10
11/// Table
12///
13/// ```rust
14/// use docx_rust::document::*;
15/// use docx_rust::formatting::*;
16///
17/// let tbl = Table::default()
18///     .property(TableProperty::default())
19///     .push_row(TableRow::default());
20/// ```
21#[derive(Debug, Default, XmlRead, XmlWrite, Clone)]
22#[cfg_attr(test, derive(PartialEq))]
23#[xml(tag = "w:tbl")]
24pub struct Table<'a> {
25    #[xml(default, child = "w:tblPr")]
26    pub property: TableProperty<'a>,
27    #[xml(child = "w:tblGrid")]
28    pub grids: TableGrid,
29    #[xml(child = "w:tr")]
30    pub rows: Vec<TableRow<'a>>,
31}
32
33impl<'a> Table<'a> {
34    __setter!(property: TableProperty<'a>);
35
36    pub fn push_row<T: Into<TableRow<'a>>>(mut self, row: T) -> Self {
37        self.rows.push(row.into());
38        self
39    }
40
41    pub fn iter_text(&self) -> impl Iterator<Item = &Cow<'a, str>> {
42        self.rows.iter().flat_map(|content| content.iter_text())
43    }
44
45    pub fn iter_text_mut(&mut self) -> impl Iterator<Item = &mut Cow<'a, str>> {
46        self.rows
47            .iter_mut()
48            .flat_map(|content| content.iter_text_mut())
49    }
50
51    pub fn replace_text<'b, I, T, S>(&mut self, dic: T) -> crate::DocxResult<()>
52    where
53        S: AsRef<str> + 'b,
54        T: IntoIterator<Item = I> + Copy,
55        I: Borrow<(S, S)>,
56    {
57        for row in self.rows.iter_mut() {
58            row.replace_text(dic)?;
59        }
60        Ok(())
61    }
62}
63
64__xml_test_suites!(
65    Table,
66    Table::default(),
67    "<w:tbl><w:tblPr/><w:tblGrid/></w:tbl>",
68    Table::default().push_row(TableRow::default()),
69    "<w:tbl><w:tblPr/><w:tblGrid/><w:tr><w:trPr/></w:tr></w:tbl>",
70);