craft-xlsx: read the styles part of a binary workbook

Package::styles() reads styles.bin into the same Styles the XML part
gives: number formats, fonts, fills, borders, cell and cell style
formats, cell styles, differential formats and indexed colours, spelled
as Excel writes them in styles.xml. A damaged part is a warning and no
styles; each table holds at most 65,536 entries.

Closes #1253.
This commit is contained in:
kiwi4boy committed 2026-11-13 23:35:18 -05:00
1 parent fd8a0dcf22
commit 3e957e0fd1
6 files changed
+764 -10

No files matched your search

+5 -2
View File
@@ -83,8 +83,11 @@ for new pictures (`vm = i + 1`) and the `XLDAPR` dynamic-array metadata (`cm = 1
The parts this crate writes use the transitional namespaces; a strict file's kept parts stay as
they were. A binary workbook is not written.
A binary workbook gives the same `Workbook`, strings, rows and merged cells. Its styles are not
read (each cell keeps its format index). Its cell formulas are decoded from their tokens into the
A binary workbook gives the same `Workbook`, strings, rows and merged cells, and the same
`Styles`: number formats, fonts, fills, borders, cell and cell style formats, cell styles,
differential formats and the indexed colours, as Excel writes them in `styles.xml` (default fill
colours and empty settings left out, a cell style format's `apply*="0"`). Custom table styles and
recent colours are not read; a damaged styles part is a warning and no styles. Its cell formulas are decoded from their tokens into the
text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as written, no implicit `@`), with
`FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell
metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the
+2 -2
View File
@@ -209,8 +209,8 @@ pub struct Document {
}
impl Document {
/// Reads every part. A binary workbook is refused: its formulas and styles are not read, so
/// it cannot be written back as SpreadsheetML without loss.
/// Reads every part. A binary workbook is refused: only some of its parts are read, so it
/// cannot be written back as SpreadsheetML without loss.
pub fn read(bytes: &[u8], limits: &Limits) -> Result<Document, Error> {
let mut p = Package::open(bytes, limits)?;
if p.is_binary() {
+16 -4
View File
@@ -214,16 +214,28 @@ impl<'a> Package<'a> {
Ok(items)
}
/// The styles part, `None` when the workbook has none (or is binary: its styles are not read).
/// The styles part, `None` when the workbook has none. A damaged one is a warning and `None`;
/// only a limit is an error.
pub fn styles(&mut self) -> Result<Option<Styles>, Error> {
if self.binary.is_some() {
return Ok(None);
}
let rels = self.workbook_rels()?;
let Some(rel) = rels.first("styles").filter(|r| !r.external) else {
self.warn("no styles part");
return Ok(None);
};
if let Some(types) = &self.binary {
let read = xlsb::check_type(types, &rel.target, xlsb::STYLES).and_then(|()| {
let bytes = self.opc.read(&rel.target)?.ok_or_else(|| xlsb::invalid(format!("missing part {}", rel.target)))?;
xlsb::styles(&bytes, &self.limits, &self.budget, &mut self.warnings)
});
return match read {
Ok(styles) => Ok(Some(styles)),
Err(Error::TooLarge(m)) => Err(Error::TooLarge(m)),
Err(e) => {
self.warn(format!("skipped {}: {e}", rel.target));
Ok(None)
}
};
}
Ok(self.optional_xml(&rel.target.clone())?.map(Styles::read))
}
+5 -1
View File
@@ -1,11 +1,13 @@
//! Binary workbooks ([MS-XLSB]): the workbook part, shared strings and worksheet cells, from
//! their records. Cell formulas are decoded from their tokens ([`formula`]) into the text an
//! `.xlsx` file holds; one that can't be keeps only its saved result, with a warning saying why.
//! Styles are not read. A record that does not parse fails the read.
//! The styles part is read into the same [`crate::styles::Styles`] ([`styles`]). A record that
//! does not parse fails the read.
mod expr;
mod formula;
mod ftab;
mod styles;
use std::collections::HashMap;
use std::sync::Arc;
@@ -19,11 +21,13 @@ use crate::workbook::{SheetEntry, SheetKind, Workbook};
use crate::{Error, Limits, Warnings};
pub(crate) use formula::Links;
use formula::{Book, Mode, Name, Xti};
pub(crate) use styles::styles;
pub(crate) const MAIN: &str = "application/vnd.ms-excel.main";
const BINARY_MAIN: &str = "application/vnd.ms-excel.sheet.binary.macroEnabled.main";
pub(crate) const WORKSHEET: &str = "application/vnd.ms-excel.worksheet";
pub(crate) const STRINGS: &str = "application/vnd.ms-excel.sharedStrings";
pub(crate) const STYLES: &str = "application/vnd.ms-excel.styles";
/// Most sheets in the workbook.
const MAX_SHEETS: usize = 1024;
/// Most merged ranges in one worksheet.
+471
View File
@@ -0,0 +1,471 @@
//! The styles part of a binary workbook (`styles.bin`, [MS-XLSB] 2.1.7.50), read into the same
//! [`Styles`] the XML part gives: what Excel writes in `styles.xml` for the same workbook. Table
//! styles, recent colours and future records are not read.
use craft_sheet::{BorderStyle, HAlign, Pattern, Script, Underline, VAlign};
use craft_xml::El;
use super::{Budget, Bytes, Records, invalid};
use crate::styles::{
Alignment, Border, BorderEdge, CellStyle, Color, ColorSource, Dxf, Fill, Font, FontScheme, GradientFill, NumFmt, PatternFill, Protection, Styles,
Xf,
};
use crate::{Error, Limits, Warnings};
/// Characters of a font name or number format kept, as the XML side keeps of a font name.
const MAX_NAME_CHARS: usize = 255;
/// Longest string read from the part (Excel's own limits are 31 and 255 characters).
const MAX_STRING_UNITS: u32 = 32_767;
/// Most stops in one gradient fill (Excel writes a handful).
const MAX_STOPS: u32 = 1024;
/// Most entries in one table of the part (Excel allows about 64,000 cell formats). Each entry is
/// an allocation, and the record allowance alone would let a small part hold millions.
const MAX_ENTRIES: usize = 65_536;
/// `BrtColor` and `XFPropColor`: the same eight bytes. `None` for "not set" (`XFPropColor` type 4).
fn color(b: &mut Bytes<'_>) -> Result<Option<Color>, Error> {
let kind = b.u8()? >> 1;
let index = b.u8()?;
let tint = i16::from_le_bytes(<[u8; 2]>::try_from(b.take(2)?).map_err(|_| invalid("truncated colour"))?);
let [r, g, bl, a] = <[u8; 4]>::try_from(b.take(4)?).map_err(|_| invalid("truncated colour"))?;
let source = match kind {
0 => ColorSource::Auto,
1 => ColorSource::Indexed(u32::from(index)),
2 => ColorSource::Rgb(u32::from_be_bytes([a, r, g, bl])),
3 => ColorSource::Theme(u32::from(index)),
_ => return Ok(None),
};
Ok(Some(Color { source, tint: (f64::from(tint) / 32767.0).clamp(-1.0, 1.0) }))
}
fn pattern(fls: u32) -> Result<Pattern, Error> {
const PATTERNS: [Pattern; 19] = [
Pattern::None,
Pattern::Solid,
Pattern::Gray50,
Pattern::Gray75,
Pattern::Gray25,
Pattern::DarkHorizontal,
Pattern::DarkVertical,
Pattern::DarkDown,
Pattern::DarkUp,
Pattern::DarkGrid,
Pattern::DarkTrellis,
Pattern::LightHorizontal,
Pattern::LightVertical,
Pattern::LightDown,
Pattern::LightUp,
Pattern::LightGrid,
Pattern::LightTrellis,
Pattern::Gray125,
Pattern::Gray0625,
];
PATTERNS.get(fls as usize).copied().ok_or_else(|| invalid("unknown fill pattern"))
}
fn border_style(dg: u16) -> Result<BorderStyle, Error> {
const STYLES: [BorderStyle; 14] = [
BorderStyle::None,
BorderStyle::Thin,
BorderStyle::Medium,
BorderStyle::Dashed,
BorderStyle::Dotted,
BorderStyle::Thick,
BorderStyle::Double,
BorderStyle::Hair,
BorderStyle::MediumDashed,
BorderStyle::DashDot,
BorderStyle::MediumDashDot,
BorderStyle::DashDotDot,
BorderStyle::MediumDashDotDot,
BorderStyle::SlantDashDot,
];
STYLES.get(usize::from(dg)).copied().ok_or_else(|| invalid("unknown border style"))
}
fn halign(alc: u32) -> Option<HAlign> {
[HAlign::General, HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Fill, HAlign::Justify, HAlign::CenterAcross, HAlign::Distributed]
.get(alc as usize)
.copied()
}
fn valign(alcv: u32) -> Option<VAlign> {
[VAlign::Top, VAlign::Center, VAlign::Bottom, VAlign::Justify, VAlign::Distributed].get(alcv as usize).copied()
}
fn underline(uls: u32) -> Underline {
match uls {
0 => Underline::None,
2 => Underline::Double,
0x21 => Underline::SingleAccounting,
0x22 => Underline::DoubleAccounting,
_ => Underline::Single,
}
}
fn script(sss: u32) -> Script {
match sss {
1 => Script::Superscript,
2 => Script::Subscript,
_ => Script::Baseline,
}
}
fn scheme(s: u32) -> Option<FontScheme> {
match s {
0 => Some(FontScheme::None),
1 => Some(FontScheme::Major),
2 => Some(FontScheme::Minor),
_ => None,
}
}
fn name(text: String) -> String {
text.chars().take(MAX_NAME_CHARS).collect()
}
/// `BrtFont`: only what Excel's `.xlsx` states for the same font (no `<b val="0"/>`, no scheme
/// `none`, no family or character set 0).
fn font(b: &mut Bytes<'_>) -> Result<Font, Error> {
let height = b.u16()?;
let flags = b.u16()?;
let weight = b.u16()?;
let sss = b.u16()?;
let uls = b.u8()?;
let family = b.u8()?;
let charset = b.u8()?;
b.u8()?;
let color = color(b)?;
let font_scheme = b.u8()?;
let font_name = name(b.text(MAX_STRING_UNITS)?);
let on = |bit: u16| (flags & bit != 0).then_some(true);
Ok(Font {
name: Some(font_name),
size: Some(f64::from(height) / 20.0),
bold: (weight >= 0x2BC).then_some(true),
italic: on(0x02),
strike: on(0x08),
outline: on(0x10),
shadow: on(0x20),
condense: on(0x40),
extend: on(0x80),
underline: (uls != 0).then(|| underline(u32::from(uls))),
vert_align: (sss != 0).then(|| script(u32::from(sss))),
color,
family: (family != 0).then_some(u32::from(family)),
charset: (charset != 0).then_some(u32::from(charset)),
scheme: scheme(u32::from(font_scheme)).filter(|s| *s != FontScheme::None),
})
}
/// A gradient's angle and inner rectangle, as `BrtFill` and `XFPropGradient` hold them.
fn gradient(b: &mut Bytes<'_>, path: bool) -> Result<GradientFill, Error> {
Ok(GradientFill { path, degree: b.f64()?, left: b.f64()?, right: b.f64()?, top: b.f64()?, bottom: b.f64()?, stops: vec![] })
}
/// `BrtFill`. Excel's `.xlsx` leaves out the default colours: system foreground (indexed 64) as
/// the pattern colour and system background (indexed 65) as the background.
fn fill(b: &mut Bytes<'_>) -> Result<Fill, Error> {
let fls = b.u32()?;
let fg = color(b)?;
let bg = color(b)?;
let kind = b.u32()?;
let mut g = gradient(b, kind == 1)?;
let count = b.u32()?;
if fls == 0x28 {
if count > MAX_STOPS {
return Err(invalid("too many gradient stops"));
}
for _ in 0..count {
let c = color(b)?.unwrap_or_default();
g.stops.push((b.f64()?, c));
}
return Ok(Fill::Gradient(g));
}
let system = |c: Color, i: u32| c.source == ColorSource::Indexed(i) && c.tint == 0.0;
Ok(Fill::Pattern(PatternFill { pattern: Some(pattern(fls)?), fg: fg.filter(|c| !system(*c, 64)), bg: bg.filter(|c| !system(*c, 65)) }))
}
/// `BrtBorder`: the five edges a cell border has, each stated (`<left/>` when it has no line).
fn border(b: &mut Bytes<'_>) -> Result<Border, Error> {
let flags = b.u8()?;
let mut edge = || -> Result<BorderEdge, Error> {
let style = border_style(u16::from(b.u8()?))?;
b.u8()?;
let c = color(b)?;
Ok(BorderEdge { style, color: c.filter(|_| style != BorderStyle::None) })
};
let (top, bottom, left, right, diagonal) = (edge()?, edge()?, edge()?, edge()?, edge()?);
Ok(Border {
left: Some(left),
right: Some(right),
top: Some(top),
bottom: Some(bottom),
diagonal: Some(diagonal),
vertical: None,
horizontal: None,
diagonal_up: flags & 2 != 0,
diagonal_down: flags & 1 != 0,
outline: true,
})
}
/// `BrtXF`. A cell style format (`style`) marks what it leaves out (`apply*="0"`); a cell format
/// marks what it sets apart from its style (`apply*="1"`).
fn xf(b: &mut Bytes<'_>, style: bool) -> Result<Xf, Error> {
const APPLY: [(u8, &str); 6] = [
(0x01, "applyNumberFormat"),
(0x02, "applyFont"),
(0x10, "applyFill"),
(0x08, "applyBorder"),
(0x04, "applyAlignment"),
(0x20, "applyProtection"),
];
let parent = b.u16()?;
let num_fmt_id = u32::from(b.u16()?);
let font_id = u32::from(b.u16()?);
let fill_id = u32::from(b.u16()?);
let border_id = u32::from(b.u16()?);
let rotation = u32::from(b.u8()?);
let indent = u32::from(b.u8()?);
let flags = u32::from(b.u16()?);
let apply = b.u8()?;
b.u8()?;
let alignment = Alignment {
horizontal: halign(flags & 7).filter(|h| *h != HAlign::General),
vertical: valign((flags >> 3) & 7).filter(|v| *v != VAlign::Bottom),
text_rotation: (rotation != 0).then_some(rotation),
wrap_text: flags & 0x40 != 0,
justify_last_line: flags & 0x80 != 0,
shrink_to_fit: flags & 0x100 != 0,
indent: (indent != 0).then_some(indent),
reading_order: Some((flags >> 10) & 3).filter(|r| *r != 0),
};
let protection = Protection { locked: (flags & 0x1000 == 0).then_some(false), hidden: (flags & 0x2000 != 0).then_some(true) };
let mut el = El::new("xf");
for (bit, attr) in APPLY {
if apply & bit != 0 {
el = el.with_attr(attr, if style { "0" } else { "1" });
}
}
Ok(Xf {
num_fmt_id,
font_id,
fill_id,
border_id,
xf_id: (!style).then_some(u32::from(parent)),
alignment: (alignment != Alignment::default()).then_some(alignment),
protection: (protection != Protection::default()).then_some(protection),
quote_prefix: flags & 0x8000 != 0,
el,
})
}
/// `BrtStyle`.
fn cell_style(b: &mut Bytes<'_>) -> Result<CellStyle, Error> {
let xf_id = b.u32()?;
let flags = b.u16()?;
let builtin = b.u8()?;
let level = b.u8()?;
let style_name = b.string(MAX_STRING_UNITS, true)?.map(name).unwrap_or_default();
let is_builtin = flags & 1 != 0;
Ok(CellStyle {
name: style_name,
xf_id,
builtin_id: is_builtin.then_some(u32::from(builtin)),
level: (is_builtin && matches!(builtin, 1 | 2)).then_some(u32::from(level)),
hidden: flags & 2 != 0,
custom_builtin: flags & 4 != 0,
})
}
/// An unsigned integer of the size a property has (1, 2 or 4 bytes).
fn uint(data: &[u8]) -> Result<u32, Error> {
match *data {
[a] => Ok(u32::from(a)),
[a, b] => Ok(u32::from(u16::from_le_bytes([a, b]))),
[a, b, c, d] => Ok(u32::from_le_bytes([a, b, c, d])),
_ => Err(invalid("unexpected formatting property size")),
}
}
/// A string with a 2-byte length (`LPWideString`, and the number format of `XFProp` 0x26).
fn short_string(b: &mut Bytes<'_>) -> Result<String, Error> {
let count = usize::from(b.u16()?);
let mut text = String::new();
for ch in char::decode_utf16(b.take(count * 2)?.as_chunks::<2>().0.iter().copied().map(u16::from_le_bytes)) {
text.push(ch.map_err(|_| invalid("invalid UTF-16 string"))?);
}
Ok(name(text))
}
fn dxf_font(d: &mut Dxf) -> &mut Font {
d.font.get_or_insert_with(Font::default)
}
/// `BrtDXF`: its `XFProps`, each stating one property.
fn dxf(b: &mut Bytes<'_>) -> Result<Dxf, Error> {
b.u16()?;
b.u16()?;
let count = b.u16()?;
let mut d = Dxf::default();
let mut gradient_fill: Option<GradientFill> = None;
let mut pattern_fill: Option<PatternFill> = None;
for _ in 0..count {
let kind = b.u16()?;
let size = usize::from(b.u16()?).checked_sub(4).ok_or_else(|| invalid("formatting property too short"))?;
let data = b.take(size)?;
let mut p = Bytes::new(data);
match kind {
0x00 => pattern_fill.get_or_insert_with(PatternFill::default).pattern = Some(pattern(uint(data)?)?),
0x01 => pattern_fill.get_or_insert_with(PatternFill::default).fg = color(&mut p)?,
0x02 => pattern_fill.get_or_insert_with(PatternFill::default).bg = color(&mut p)?,
0x03 => {
let path = p.u32()? == 1;
gradient_fill = Some(gradient(&mut p, path)?);
}
0x04 => {
let g = gradient_fill.as_mut().ok_or_else(|| invalid("gradient stop without a gradient"))?;
if g.stops.len() >= MAX_STOPS as usize {
return Err(invalid("too many gradient stops"));
}
p.u16()?;
let position = p.f64()?;
g.stops.push((position, color(&mut p)?.unwrap_or_default()));
}
0x05 => dxf_font(&mut d).color = color(&mut p)?,
0x06..=0x0C => {
let c = color(&mut p)?;
let edge = Some(BorderEdge { style: border_style(p.u16()?)?, color: c });
let border = d.border.get_or_insert_with(|| Border { outline: true, ..Border::default() });
match kind {
0x06 => border.top = edge,
0x07 => border.bottom = edge,
0x08 => border.left = edge,
0x09 => border.right = edge,
0x0A => border.diagonal = edge,
0x0B => border.vertical = edge,
_ => border.horizontal = edge,
}
}
0x0D => d.border.get_or_insert_with(|| Border { outline: true, ..Border::default() }).diagonal_up = uint(data)? != 0,
0x0E => d.border.get_or_insert_with(|| Border { outline: true, ..Border::default() }).diagonal_down = uint(data)? != 0,
0x0F..=0x16 => {
let v = uint(data)?;
let a = d.alignment.get_or_insert_with(Alignment::default);
match kind {
0x0F => a.horizontal = halign(v),
0x10 => a.vertical = valign(v),
0x11 => a.text_rotation = Some(v),
0x12 => a.indent = Some(v),
0x13 => a.reading_order = Some(v),
0x14 => a.wrap_text = v != 0,
0x15 => a.justify_last_line = v != 0,
_ => a.shrink_to_fit = v != 0,
}
}
0x18 => dxf_font(&mut d).name = Some(short_string(&mut p)?),
0x19 => dxf_font(&mut d).bold = Some(uint(data)? >= 0x2BC),
0x1A => dxf_font(&mut d).underline = Some(underline(uint(data)?)),
0x1B => dxf_font(&mut d).vert_align = Some(script(uint(data)?)),
0x1C => dxf_font(&mut d).italic = Some(uint(data)? != 0),
0x1D => dxf_font(&mut d).strike = Some(uint(data)? != 0),
0x1E => dxf_font(&mut d).outline = Some(uint(data)? != 0),
0x1F => dxf_font(&mut d).shadow = Some(uint(data)? != 0),
0x20 => dxf_font(&mut d).condense = Some(uint(data)? != 0),
0x21 => dxf_font(&mut d).extend = Some(uint(data)? != 0),
0x22 => dxf_font(&mut d).charset = Some(uint(data)?),
0x23 => dxf_font(&mut d).family = Some(uint(data)?),
0x24 => dxf_font(&mut d).size = Some(f64::from(uint(data)?) / 20.0),
0x25 => dxf_font(&mut d).scheme = scheme(uint(data)?),
0x26 => d.num_fmt.get_or_insert_with(NumFmt::default).code = Some(short_string(&mut p)?),
0x29 => d.num_fmt.get_or_insert_with(NumFmt::default).id = Some(uint(data)?),
0x2B => d.protection.get_or_insert_with(Protection::default).locked = Some(uint(data)? != 0),
0x2C => d.protection.get_or_insert_with(Protection::default).hidden = Some(uint(data)? != 0),
// Merged cells (0x17) and relative indents (0x2A) have no place in `<dxf>`.
_ => {}
}
}
d.fill = gradient_fill.map(Fill::Gradient).or(pattern_fill.map(Fill::Pattern));
Ok(d)
}
/// The styles part: `BrtBeginStyleSheet` to `BrtEndStyleSheet`.
pub(crate) fn styles(bytes: &[u8], limits: &Limits, budget: &Budget, warnings: &mut Warnings) -> Result<Styles, Error> {
let mut records = Records::new(bytes, limits, budget);
records.first(278, warnings)?;
let mut s = Styles::default();
// Inside BrtBeginCellStyleXFs (true) or BrtBeginCellXFs (false).
let mut xfs: Option<bool> = None;
let mut palette = false;
while let Some((id, payload)) = records.next(warnings)? {
let mut b = Bytes::new(payload);
let entries = match id {
44 => s.num_fmts.len(),
43 => s.fonts.len(),
45 => s.fills.len(),
46 => s.borders.len(),
47 => s.cell_style_xfs.len().max(s.cell_xfs.len()),
48 => s.cell_styles.len(),
507 => s.dxfs.len(),
475 => s.indexed_colors.len(),
_ => 0,
};
if entries >= MAX_ENTRIES {
return Err(invalid(format!("more than {MAX_ENTRIES} entries in a styles table")));
}
match id {
279 => {
records.end(payload, warnings)?;
return Ok(s);
}
44 => {
let id = u32::from(b.u16()?);
let code = name(b.text(MAX_STRING_UNITS)?);
budget.text(code.len(), limits)?;
s.num_fmts.push((id, code));
}
43 => {
let f = font(&mut b)?;
budget.text(f.name.as_ref().map_or(0, String::len), limits)?;
s.fonts.push(f);
}
45 => s.fills.push(fill(&mut b)?),
46 => s.borders.push(border(&mut b)?),
626 => xfs = Some(true),
617 => xfs = Some(false),
627 | 618 => xfs = None,
47 => match xfs {
Some(true) => s.cell_style_xfs.push(xf(&mut b, true)?),
Some(false) => s.cell_xfs.push(xf(&mut b, false)?),
None => return Err(invalid("cell format outside its list")),
},
48 => {
let c = cell_style(&mut b)?;
budget.text(c.name.len(), limits)?;
s.cell_styles.push(c);
}
507 => s.dxfs.push(dxf(&mut b)?),
// BrtBeginIndexedColors, BrtEndIndexedColors.
565 => palette = true,
566 => palette = false,
475 if palette => {
let [r, g, bl, _] = <[u8; 4]>::try_from(b.take(4)?).map_err(|_| invalid("truncated colour"))?;
s.indexed_colors.push(u32::from_be_bytes([0, r, g, bl]));
}
// BrtBeginTableStyles: the count of custom table styles, which are not read.
508 => {
if b.u32()? > 0 {
warnings.warn("custom table styles in a binary workbook were not read");
}
continue;
}
_ => continue,
}
// The records read above are read whole; the rest are skipped.
if matches!(id, 44 | 43 | 45 | 46 | 47 | 48 | 507 | 475) {
b.finish()?;
}
}
Err(invalid("missing styles end record"))
}
+265 -1
View File
@@ -5,7 +5,10 @@ mod common;
use common::{read, read_with};
use craft_xlsx::testing::zip;
use craft_xlsx::{CellError, CellRef, Error, FormulaKind, Limits, Range, SheetKind, Value, Visibility, is_xlsb};
use craft_xlsx::{
CellError, CellRef, Color, ColorSource, Error, Fill, FormulaKind, Limits, Package, Pattern, PatternFill, Protection, Range, SheetKind, Styles,
Value, Visibility, is_xlsb,
};
const ROOT: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="book" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="records/book.bin"/></Relationships>"#;
const RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="one" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/one.bin"/><Relationship Id="two" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/two.bin"/><Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="../text/strings.bin"/></Relationships>"#;
@@ -930,3 +933,264 @@ fn a_dynamic_array_kept_as_its_value_has_no_cell_metadata() {
assert_eq!(sheet.cell_metadata.iter().collect::<Vec<_>>(), [(&at("C1"), &1)]);
assert!(warned(&wb, "missing from the file"), "{:?}", wb.warnings);
}
// Styles ([MS-XLSB] 2.1.7.50): a styles part assembled from records, and the `styles.xml` Excel
// writes for the same formats when it saves the workbook as `.xlsx`.
const STYLES_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="one" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/one.bin"/><Relationship Id="two" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="../data/two.bin"/><Relationship Id="styles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="../look/styles.bin"/></Relationships>"#;
const STYLES_TYPES: &str = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/records/book.bin" ContentType="application/vnd.ms-excel.sheet.binary.macroEnabled.main"/><Override PartName="/data/one.bin" ContentType="application/vnd.ms-excel.worksheet"/><Override PartName="/data/two.bin" ContentType="application/vnd.ms-excel.worksheet"/><Override PartName="/look/styles.bin" ContentType="application/vnd.ms-excel.styles"/></Types>"#;
fn styled_file(styles: &[u8], types: &str) -> Vec<u8> {
let sheet = worksheet(&[row(0), cell(5, 0, &1.0f64.to_le_bytes())].concat(), &[]);
zip(&[
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", ROOT.as_bytes()),
("records/book.bin", &book(false)),
("records/_rels/book.bin.rels", STYLES_RELS.as_bytes()),
("data/one.bin", &sheet),
("data/two.bin", &worksheet(&[], &[])),
("look/styles.bin", styles),
])
}
/// The styles part of a package, and the warnings reading it gave.
fn styles_of(bytes: &[u8]) -> (Option<Styles>, Vec<String>) {
let mut p = Package::open(bytes, &Limits::default()).unwrap();
let styles = p.styles().unwrap();
(styles, p.warnings().to_vec())
}
/// `BrtColor`: auto 0, indexed 1, RGB 2, theme 3.
fn color(kind: u8, index: u8, tint: i16, rgba: [u8; 4]) -> Vec<u8> {
[&[kind << 1 | 1, index][..], &tint.to_le_bytes(), &rgba].concat()
}
fn indexed(i: u8) -> Vec<u8> {
color(1, i, 0, [0, 0, 0, 255])
}
fn theme(i: u8, tint: i16) -> Vec<u8> {
color(3, i, tint, [0, 0, 0, 255])
}
fn rgb(r: u8, g: u8, b: u8) -> Vec<u8> {
color(2, 255, 0, [r, g, b, 255])
}
#[allow(clippy::too_many_arguments)]
fn font(twips: u16, flags: u16, weight: u16, script: u16, underline: u8, family: u8, charset: u8, c: &[u8], scheme: u8, name: &str) -> Vec<u8> {
let head =
[&twips.to_le_bytes()[..], &flags.to_le_bytes(), &weight.to_le_bytes(), &script.to_le_bytes(), &[underline, family, charset, 0]].concat();
record(43, &[&head[..], c, &[scheme], &wide(name)].concat())
}
fn pattern_fill(fls: u32, fg: &[u8], bg: &[u8]) -> Vec<u8> {
record(45, &[&fls.to_le_bytes()[..], fg, bg, &[0; 48]].concat())
}
fn edge(dg: u8, c: &[u8]) -> Vec<u8> {
[&[dg, 0][..], c].concat()
}
#[allow(clippy::too_many_arguments)]
fn brt_xf(parent: u16, fmt: u16, font: u16, fill: u16, border: u16, rotation: u8, indent: u8, flags: u16, apply: u8) -> Vec<u8> {
let ids = [parent, fmt, font, fill, border].map(u16::to_le_bytes).concat();
record(47, &[&ids[..], &[rotation, indent], &flags.to_le_bytes(), &[apply, 0]].concat())
}
fn style(xf: u32, flags: u16, builtin: u8, level: u8, name: &str) -> Vec<u8> {
record(48, &[&xf.to_le_bytes()[..], &flags.to_le_bytes(), &[builtin, level], &wide(name)].concat())
}
fn prop(kind: u16, data: &[u8]) -> Vec<u8> {
[&kind.to_le_bytes()[..], &(data.len() as u16 + 4).to_le_bytes(), data].concat()
}
fn short(text: &str) -> Vec<u8> {
let units: Vec<u16> = text.encode_utf16().collect();
[(units.len() as u16).to_le_bytes().to_vec(), units.iter().flat_map(|u| u.to_le_bytes()).collect()].concat()
}
fn brt_dxf(props: &[Vec<u8>]) -> Vec<u8> {
record(507, &[&[0, 0x80, 0, 0][..], &(props.len() as u16).to_le_bytes(), &props.concat()].concat())
}
fn begin(id: u16, count: u32) -> Vec<u8> {
record(id, &count.to_le_bytes())
}
/// Every kind of record the styles part has, as Excel writes them.
fn styles_bin() -> Vec<u8> {
let normal = font(220, 0, 400, 0, 0, 2, 0, &theme(1, 0), 2, "Aptos Narrow");
// Bold, italic, struck out, superscript, double accounting underline; family and
// character set 0 and scheme "none" are not written in `.xlsx`.
let fancy = font(290, 0x0A, 700, 1, 0x22, 0, 2, &rgb(0, 128, 255), 0, "Wingdings");
let heading = font(220, 0, 400, 0, 0, 2, 0, &theme(4, 13106), 1, "Aptos Display");
let gradient = [
&0x28u32.to_le_bytes()[..],
&indexed(64),
&indexed(65),
&1u32.to_le_bytes(),
&[0.0f64, 0.5, 0.5, 0.5, 0.5].map(f64::to_le_bytes).concat(),
&2u32.to_le_bytes(),
&theme(0, 0),
&0.0f64.to_le_bytes(),
&theme(4, 0),
&1.0f64.to_le_bytes(),
]
.concat();
let none = edge(0, &color(0, 0, 0, [0, 0, 0, 0]));
let parts: Vec<Vec<u8>> = vec![
record(278, &[]),
begin(615, 1),
record(44, &[&164u16.to_le_bytes()[..], &wide(r"yyyy\-mm\-dd")].concat()),
record(616, &[]),
begin(611, 3),
normal,
fancy,
heading,
record(612, &[]),
begin(603, 5),
pattern_fill(0, &indexed(64), &indexed(65)),
pattern_fill(17, &indexed(64), &indexed(65)),
pattern_fill(1, &rgb(255, 255, 0), &indexed(64)),
pattern_fill(9, &theme(5, -8191), &indexed(65)),
record(45, &gradient),
record(604, &[]),
begin(613, 2),
record(46, &[&[0][..], &none, &none, &none, &none, &none].concat()),
record(
46,
&[&[3][..], &edge(2, &rgb(200, 0, 0)), &none, &edge(7, &indexed(64)), &edge(13, &color(0, 0, 0, [0, 0, 0, 0])), &edge(1, &theme(4, 0))]
.concat(),
),
record(614, &[]),
begin(626, 3),
brt_xf(0xFFFF, 0, 0, 0, 0, 0, 0, 0x1010, 0),
brt_xf(0xFFFF, 9, 0, 0, 0, 0, 0, 0x1010, 0x3E),
brt_xf(0xFFFF, 0, 2, 0, 0, 0, 0, 0x1010, 0),
record(627, &[]),
begin(617, 4),
brt_xf(0, 0, 0, 0, 0, 0, 0, 0x1010, 0),
brt_xf(0, 164, 0, 0, 0, 0, 0, 0x1010, 0x01),
// Left, top, wrapped, shrunk, right to left, unlocked, hidden, quote prefix.
brt_xf(0, 0, 0, 0, 0, 180, 2, 0x01 | 0x40 | 0x100 | 0x800 | 0x2000 | 0x8000, 0x24),
brt_xf(1, 0, 1, 4, 1, 0, 0, 0x1010, 0x1A),
record(618, &[]),
begin(619, 3),
style(0, 1, 0, 0, "Normal"),
// Excel wraps each style in alternate content, which is skipped.
record(37, &[1, 0, 2, 0x0e, 0, 0x80]),
record(3072, &[0; 16]),
record(38, &[]),
style(1, 1 | 4, 1, 1, "RowLevel_2"),
style(2, 2, 0, 0, "Probe Style"),
record(620, &[]),
begin(505, 2),
brt_dxf(&[
prop(0x05, &rgb(0x9C, 0, 6)),
prop(0x19, &700u16.to_le_bytes()),
prop(0x1C, &[0]),
prop(0x1A, &0x21u16.to_le_bytes()),
prop(0x24, &240u32.to_le_bytes()),
prop(0x18, &short("Arial")),
prop(0x29, &170u16.to_le_bytes()),
prop(0x26, &short("0.0")),
prop(0x02, &rgb(0xFF, 0xC7, 0xCE)),
prop(0x0F, &[2]),
prop(0x14, &[1]),
prop(0x2B, &[0]),
prop(0x07, &[&color(0, 0, 0, [0, 0, 0, 0])[..], &1u16.to_le_bytes()].concat()),
]),
brt_dxf(&[
prop(0x03, &[&0u32.to_le_bytes()[..], &[90.0f64, 0.0, 0.0, 0.0, 0.0].map(f64::to_le_bytes).concat()].concat()),
prop(0x04, &[&[0, 0][..], &0.0f64.to_le_bytes(), &rgb(255, 255, 255)].concat()),
prop(0x04, &[&[0, 0][..], &1.0f64.to_le_bytes(), &theme(4, 0)].concat()),
]),
record(506, &[]),
record(508, &[&0u32.to_le_bytes()[..], &wide("TableStyleMedium2"), &wide("PivotStyleLight16")].concat()),
record(509, &[]),
record(473, &[]),
record(565, &[]),
record(475, &[0x11, 0x22, 0x33, 0]),
record(475, &[0xFF, 0xFF, 0xFF, 0]),
record(566, &[]),
record(474, &[]),
record(279, &[]),
];
parts.concat()
}
const STYLES_XML: &str = r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="yyyy\-mm\-dd"/></numFmts><fonts count="3"><font><sz val="11"/><color theme="1"/><name val="Aptos Narrow"/><family val="2"/><scheme val="minor"/></font><font><b/><i/><strike/><u val="doubleAccounting"/><vertAlign val="superscript"/><sz val="14.5"/><color rgb="FF0080FF"/><name val="Wingdings"/><charset val="2"/></font><font><sz val="11"/><color theme="4" tint="0.39997558519241921"/><name val="Aptos Display"/><family val="2"/><scheme val="major"/></font></fonts><fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FFFFFF00"/><bgColor indexed="64"/></patternFill></fill><fill><patternFill patternType="darkGrid"><fgColor theme="5" tint="-0.249977111117893"/></patternFill></fill><fill><gradientFill type="path" left="0.5" right="0.5" top="0.5" bottom="0.5"><stop position="0"><color theme="0"/></stop><stop position="1"><color theme="4"/></stop></gradientFill></fill></fills><borders count="2"><border><left/><right/><top/><bottom/><diagonal/></border><border diagonalUp="1" diagonalDown="1"><left style="hair"><color indexed="64"/></left><right style="slantDashDot"><color auto="1"/></right><top style="medium"><color rgb="FFC80000"/></top><bottom/><diagonal style="thin"><color theme="4"/></diagonal></border></borders><cellStyleXfs count="3"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/><xf numFmtId="9" fontId="0" fillId="0" borderId="0" applyFont="0" applyFill="0" applyBorder="0" applyAlignment="0" applyProtection="0"/><xf numFmtId="0" fontId="2" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="4"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" quotePrefix="1" applyAlignment="1" applyProtection="1"><alignment horizontal="left" vertical="top" textRotation="180" wrapText="1" indent="2" shrinkToFit="1" readingOrder="2"/><protection locked="0" hidden="1"/></xf><xf numFmtId="0" fontId="1" fillId="4" borderId="1" xfId="1" applyFont="1" applyFill="1" applyBorder="1"/></cellXfs><cellStyles count="3"><cellStyle name="Normal" xfId="0" builtinId="0"/><cellStyle name="RowLevel_2" xfId="1" builtinId="1" iLevel="1" customBuiltin="1"/><cellStyle name="Probe Style" xfId="2" hidden="1"/></cellStyles><dxfs count="2"><dxf><font><b/><i val="0"/><u val="singleAccounting"/><sz val="12"/><color rgb="FF9C0006"/><name val="Arial"/></font><numFmt numFmtId="170" formatCode="0.0"/><fill><patternFill><bgColor rgb="FFFFC7CE"/></patternFill></fill><alignment horizontal="center" wrapText="1"/><protection locked="0"/><border><bottom style="thin"><color auto="1"/></bottom></border></dxf><dxf><fill><gradientFill degree="90"><stop position="0"><color rgb="FFFFFFFF"/></stop><stop position="1"><color theme="4"/></stop></gradientFill></fill></dxf></dxfs><colors><indexedColors><rgbColor rgb="00112233"/><rgbColor rgb="00FFFFFF"/></indexedColors></colors></styleSheet>"#;
/// The same styles from a SpreadsheetML package.
fn xml_styles(xml: &str) -> Styles {
let types = r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>"#;
let root = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#;
let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#;
let bytes = zip(&[
("[Content_Types].xml", types.as_bytes()),
("_rels/.rels", root.as_bytes()),
("xl/workbook.xml", br#"<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>"#),
("xl/_rels/workbook.xml.rels", rels.as_bytes()),
("xl/styles.xml", xml.as_bytes()),
]);
styles_of(&bytes).0.unwrap()
}
/// What both readers lift out: an `<xf>`'s element keeps only its `apply*` flags, and the XML
/// part's own element is dropped.
fn lifted(mut s: Styles) -> Styles {
for xf in s.cell_style_xfs.iter_mut().chain(&mut s.cell_xfs) {
let attrs = xf.el.attrs.iter().filter(|(k, _)| k.starts_with("apply")).cloned().collect();
xf.el = craft_xml::El::new("xf");
xf.el.attrs = attrs;
}
s.root = craft_xml::El::default();
s
}
#[test]
fn styles_are_read_as_their_xlsx_spelling() {
let (binary, warnings) = styles_of(&styled_file(&styles_bin(), STYLES_TYPES));
let binary = binary.expect("styles are read");
assert_eq!(lifted(binary.clone()), lifted(xml_styles(STYLES_XML)));
// A few of the conversions, spelled out.
assert_eq!(binary.fonts[1].size, Some(14.5));
assert_eq!(binary.fonts[1].family, None);
let solid = Fill::Pattern(PatternFill {
pattern: Some(Pattern::Solid),
fg: Some(Color { source: ColorSource::Rgb(0xFFFF_FF00), tint: 0.0 }),
bg: Some(Color { source: ColorSource::Indexed(64), tint: 0.0 }),
});
assert_eq!(binary.fills[2], solid);
assert_eq!(binary.cell_xfs[2].protection, Some(Protection { locked: Some(false), hidden: Some(true) }));
assert_eq!(binary.palette()[0], 0x11_2233);
// Written back as SpreadsheetML, a cell style format says what it leaves out, as Excel's does.
let written = String::from_utf8(binary.to_xml()).unwrap();
assert!(written.contains(r#"applyFont="0" applyFill="0" applyBorder="0" applyAlignment="0" applyProtection="0""#), "{written}");
assert!(warnings.iter().any(|w| w.contains("alternate-content")), "{warnings:?}");
assert!(!warnings.iter().any(|w| w.contains("table styles")), "{warnings:?}");
}
#[test]
fn damaged_styles_are_a_warning_and_the_workbook_opens() {
let good = styles_bin();
let end = record(279, &[]);
let body = &good[..good.len() - end.len()];
let with = |extra: &[u8]| [body, extra, &end].concat();
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
("truncated", good[..good.len() - 1].to_vec(), STYLES_TYPES),
("no end record", body.to_vec(), STYLES_TYPES),
("unknown fill pattern", with(&pattern_fill(99, &indexed(64), &indexed(65))), STYLES_TYPES),
("unknown border style", with(&record(46, &[&[0][..], &edge(14, &indexed(64)), &[0; 40]].concat())), STYLES_TYPES),
("cell format outside its list", with(&brt_xf(0, 0, 0, 0, 0, 0, 0, 0x1010, 0)), STYLES_TYPES),
("short property", with(&brt_dxf(&[vec![0x19, 0, 2, 0]])), STYLES_TYPES),
("wrong content type", good.clone(), TYPES),
];
for (why, part, types) in cases {
let bytes = styled_file(&part, types);
let (styles, warnings) = styles_of(&bytes);
assert!(styles.is_none(), "{why}");
assert!(warnings.iter().any(|w| w.contains("look/styles.bin")), "{why}: {warnings:?}");
assert_eq!(read(&bytes).unwrap().sheets[0].value(CellRef::new(0, 0)), Value::Number(1.0), "{why}");
}
// A table past 65,536 entries is refused before it is held.
let xfs = brt_xf(0, 0, 0, 0, 0, 0, 0, 0x1010, 0).repeat(65_537);
let (styles, warnings) = styles_of(&styled_file(&with(&[&begin(617, 65_537)[..], &xfs, &record(618, &[])].concat()), STYLES_TYPES));
assert!(styles.is_none());
assert!(warnings.iter().any(|w| w.contains("65536 entries")), "{warnings:?}");
// Custom table styles are not read, and say so.
let table_styles = [body, &record(508, &[&1u32.to_le_bytes()[..], &wide("Probe Table"), &wide("")].concat()), &end].concat();
let (styles, warnings) = styles_of(&styled_file(&table_styles, STYLES_TYPES));
assert!(styles.is_some());
assert!(warnings.iter().any(|w| w.contains("table styles")), "{warnings:?}");
}