craft-xlsx: binary styles: legacy number formats, automatic font colours, tinted fills

A broader Excel probe found three differences from the styles.xml Excel
writes for the same workbook:

- A number format with a newer locale tag ([$-ja-JP-x-gannen]) is only in
  alternate content: the newer spelling in a block for later versions, and
  the one .xlsx keeps as formatCode in a block listing version 12 onwards.
  The styles part now reads the alternate content meant for Excel 2007
  (version 12), so the format is no longer lost.
- A font whose colour is automatic has no <color> in .xlsx.
- A pattern fill whose pattern colour has a tint states the system
  background (bgColor indexed 65), as Excel's .xlsx does for any pattern.
This commit is contained in:
kiwi4boy committed 2026-11-14 11:32:40 -05:00
1 parent 3e957e0fd1
commit d2b6416db9
4 files changed
+50 -15

No files matched your search

+2 -1
View File
@@ -86,7 +86,8 @@ they were. A binary workbook is not written.
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
colours and empty settings left out, a cell style format's `apply*="0"`, a number format with a
newer locale tag in its Excel 2007 spelling, as `formatCode` has it). 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
+22 -7
View File
@@ -175,12 +175,16 @@ struct Records<'a, 'l> {
bytes: Bytes<'a>,
limits: &'l Limits,
budget: &'l Budget,
blocks: Vec<u16>,
/// Each open block's end record, and whether its records are read.
blocks: Vec<(u16, bool)>,
/// Read the alternate content meant for Excel 2007 (version 12), as an `.xlsx` reader sees
/// the main attribute where Excel keeps a newer spelling in an extension.
excel_2007: bool,
}
impl<'a, 'l> Records<'a, 'l> {
fn new(bytes: &'a [u8], limits: &'l Limits, budget: &'l Budget) -> Self {
Self { bytes: Bytes::new(bytes), limits, budget, blocks: vec![] }
Self { bytes: Bytes::new(bytes), limits, budget, blocks: vec![], excel_2007: false }
}
fn next(&mut self, warnings: &mut Warnings) -> Result<Option<(u16, &'a [u8])>, Error> {
@@ -209,6 +213,7 @@ impl<'a, 'l> Records<'a, 'l> {
// BrtFRTBegin, BrtACBegin.
35 | 37 => {
let mut b = Bytes::new(payload);
let mut read = false;
if id == 35 {
b.take(4)?;
} else {
@@ -216,22 +221,32 @@ impl<'a, 'l> Records<'a, 'l> {
if count == 0 {
return Err(invalid("empty alternate-content version list"));
}
b.take(usize::from(count) * 4)?;
// ACProductVersion: fileVersion, then fileProduct (15 bits) and
// fileExtension (the version and later).
for _ in 0..count {
let (version, product) = (b.u16()?, b.u16()?);
let later = product & 0x8000 != 0;
read |= self.excel_2007 && product & 0x7FFF == 0 && (version == 12 || later && version <= 12);
}
}
b.finish()?;
if self.blocks.len() >= 64 {
return Err(invalid("extension blocks nested too deeply"));
}
self.blocks.push(id + 1);
warnings.warn("unsupported XLSB future-record and alternate-content blocks were skipped");
// Inside a skipped block, everything is skipped.
let read = read && self.blocks.iter().all(|(_, r)| *r);
self.blocks.push((id + 1, read));
if !read {
warnings.warn("unsupported XLSB future-record and alternate-content blocks were skipped");
}
}
// BrtFRTEnd, BrtACEnd.
36 | 38 => {
if self.blocks.pop() != Some(id) || !payload.is_empty() {
if self.blocks.pop().map(|(end, _)| end) != Some(id) || !payload.is_empty() {
return Err(invalid("mismatched extension block end"));
}
}
_ if !self.blocks.is_empty() => {}
_ if self.blocks.iter().any(|(_, read)| !read) => {}
_ => return Ok(Some((id, payload))),
}
}
+9 -3
View File
@@ -151,10 +151,11 @@ fn font(b: &mut Bytes<'_>) -> Result<Font, Error> {
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),
// An automatic colour is a font with no `<color>` in `.xlsx`.
color: color.filter(|c| c.source != ColorSource::Auto),
})
}
@@ -164,7 +165,8 @@ fn gradient(b: &mut Bytes<'_>, path: bool) -> Result<GradientFill, Error> {
}
/// `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.
/// the pattern colour and system background (indexed 65) as the background, unless the pattern
/// colour has a tint (as the built-in "20% - Accent1" styles do), when it states the background.
fn fill(b: &mut Bytes<'_>) -> Result<Fill, Error> {
let fls = b.u32()?;
let fg = color(b)?;
@@ -183,7 +185,8 @@ fn fill(b: &mut Bytes<'_>) -> Result<Fill, Error> {
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)) }))
let tinted = fg.is_some_and(|c| c.tint != 0.0);
Ok(Fill::Pattern(PatternFill { pattern: Some(pattern(fls)?), fg: fg.filter(|c| !system(*c, 64)), bg: bg.filter(|c| tinted || !system(*c, 65)) }))
}
/// `BrtBorder`: the five edges a cell border has, each stated (`<left/>` when it has no line).
@@ -393,6 +396,9 @@ fn dxf(b: &mut Bytes<'_>) -> Result<Dxf, Error> {
/// 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);
// Excel keeps a number format with a newer locale tag in two alternate-content blocks: the
// newer spelling for itself, and for Excel 2007 the one `.xlsx` has as `formatCode`.
records.excel_2007 = true;
records.first(278, warnings)?;
let mut s = Styles::default();
// Inside BrtBeginCellStyleXFs (true) or BrtBeginCellXFs (false).
+17 -4
View File
@@ -1014,6 +1014,8 @@ fn styles_bin() -> Vec<u8> {
// 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");
// An automatic colour: no `<color>` in `.xlsx`.
let auto = font(220, 0x02, 400, 0, 0, 2, 0, &color(0, 64, 0, [0, 0, 0, 255]), 2, "Aptos Narrow");
let gradient = [
&0x28u32.to_le_bytes()[..],
&indexed(64),
@@ -1030,20 +1032,31 @@ fn styles_bin() -> Vec<u8> {
let none = edge(0, &color(0, 0, 0, [0, 0, 0, 0]));
let parts: Vec<Vec<u8>> = vec![
record(278, &[]),
begin(615, 1),
begin(615, 2),
record(44, &[&164u16.to_le_bytes()[..], &wide(r"yyyy\-mm\-dd")].concat()),
// A format in two alternate-content blocks: the newer spelling for version 13 and later
// (skipped), and the one for versions 12 and 13, which `.xlsx` has as `formatCode`.
record(37, &[1, 0, 13, 0, 0, 0x80]),
record(44, &[&165u16.to_le_bytes()[..], &wide("[$-ja-JP-x-gannen]ge")].concat()),
record(38, &[]),
record(37, &[2, 0, 12, 0, 0, 0, 13, 0, 0, 0]),
record(44, &[&165u16.to_le_bytes()[..], &wide("[$]ge")].concat()),
record(38, &[]),
record(616, &[]),
begin(611, 3),
begin(611, 4),
normal,
fancy,
heading,
auto,
record(612, &[]),
begin(603, 5),
begin(603, 6),
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),
// A tinted pattern colour: `.xlsx` states the system background, as for darkGrid above.
pattern_fill(1, &theme(4, 26213), &indexed(65)),
record(604, &[]),
begin(613, 2),
record(46, &[&[0][..], &none, &none, &none, &none, &none].concat()),
@@ -1109,7 +1122,7 @@ fn styles_bin() -> Vec<u8> {
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>"#;
const STYLES_XML: &str = r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="2"><numFmt numFmtId="164" formatCode="yyyy\-mm\-dd"/><numFmt numFmtId="165" formatCode="[$]ge"/></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><font><i/><sz val="11"/><name val="Aptos Narrow"/><family val="2"/><scheme val="minor"/></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"/><bgColor indexed="65"/></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><fill><patternFill patternType="solid"><fgColor theme="4" tint="0.79998168889431442"/><bgColor indexed="65"/></patternFill></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 {