Replace the styles parts in a word processing document

Replacing styles means copying or rewriting word/styles.xml and keeping the main document relationship intact.

Word 2013 and later documents can contain both styles.xml and stylesWithEffects.xml. To round-trip across Word versions, replace both parts when the source and target both contain them.

Rust workflow

Create or reuse the normal styles part, then replace its XML payload:

#![allow(unused)]
fn main() {
pub fn replace_styles_part(
  path: &Path,
  styles_xml: &str,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
  if !styles_xml.contains("<w:styles") {
    return Err("styles XML must contain a w:styles root".into());
  }

  let mut document = WordprocessingDocument::new_from_file_with_settings(path, lazy_settings())?;
  let main_part = document.main_document_part()?;
  let styles_part = if let Some(part) = main_part.style_definitions_part(&document) {
    part
  } else {
    main_part.add_new_part_auto_id::<_, StyleDefinitionsPart>(&mut document)?
  };

  styles_part.set_data(&mut document, styles_xml.as_bytes().to_vec())?;

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

The upstream workflow extracts a complete styles part from a source document, then writes that XML into the target styles part. If the requested target part does not exist, decide whether to create it or return an explicit error. Replacing styles can change document appearance immediately because paragraphs, runs, tables, and numbering reference style ids.

In ooxmlsdk, use MainDocumentPart::style_definitions_part(&document) for the normal styles part and MainDocumentPart::styles_with_effects_part(&document) when present.