Insert a table into a word processing document

Inserting a table is a main document edit. The table must be placed in the body before section properties and should contain valid cell content.

Tables are represented by tbl elements. A table includes table-wide properties (tblPr) and can also contain a table grid (tblGrid), rows (tr), cells (tc), optional cell properties (tcPr), and paragraphs inside each cell.

Table markup

<w:tbl>
  <w:tblPr>
    <w:tblW w:w="5000" w:type="pct"/>
    <w:tblBorders>
      <w:top w:val="single" w:sz="4"/>
      <w:left w:val="single" w:sz="4"/>
      <w:bottom w:val="single" w:sz="4"/>
      <w:right w:val="single" w:sz="4"/>
    </w:tblBorders>
  </w:tblPr>
  <w:tblGrid>
    <w:gridCol w:w="10296"/>
  </w:tblGrid>
  <w:tr>
    <w:tc>
      <w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>
      <w:p><w:r><w:t>Hello, World!</w:t></w:r></w:p>
    </w:tc>
  </w:tr>
</w:tbl>

Rust workflow

#![allow(unused)]
fn main() {
pub fn insert_table(path: &Path, rows: &[&[&str]]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
  let mut document = WordprocessingDocument::new_from_file_with_settings(path, lazy_settings())?;
  let main_part = document.main_document_part()?;
  let xml = main_part.data_as_str(&document)?.unwrap_or_default();
  let table = table_xml(rows);
  let updated_xml = insert_before_section_properties(xml, &table)?;

  main_part.set_data(&mut document, updated_xml.into_bytes())?;

  let mut buffer = Cursor::new(Vec::new());
  document.save(&mut buffer)?;
  Ok(buffer.into_inner())
}
}

The sample flow creates table properties, adds border elements, creates a row, creates a cell with width properties and a paragraph/run/text child, then appends the table to the document body. If cloning cells, clone XML structure carefully so relationship-backed content is not duplicated incorrectly.

In ooxmlsdk, generated schema types include Table, TableProperties, TableWidth, TableBorders, TopBorder, LeftBorder, BottomBorder, RightBorder, TableGrid, GridColumn, TableRow, TableCell, TableCellProperties, TableCellWidth, Paragraph, Run, and Text.