use std::collections::{HashMap, HashSet};
use std::io::BufRead;
use quick_xml::Reader;
use quick_xml::events::{BytesStart, Event};
use crate::error::Result;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CellStyle {
pub bold: bool,
pub italic: bool,
pub font_color: Option<u32>,
pub background: Option<u32>,
}
#[derive(Debug, Default)]
pub struct Styles {
date_styles: HashSet<u32>,
cell_styles: Vec<CellStyle>,
dxfs: Vec<CellStyle>,
}
impl Styles {
pub fn empty() -> Self {
Self::default()
}
pub fn is_date(&self, style: u32) -> bool {
self.date_styles.contains(&style)
}
pub fn cell_style(&self, style: u32) -> CellStyle {
self.cell_styles
.get(style as usize)
.copied()
.unwrap_or_default()
}
pub fn dxf_style(&self, dxf_id: u32) -> CellStyle {
self.dxfs.get(dxf_id as usize).copied().unwrap_or_default()
}
pub fn parse<R: BufRead>(reader: R) -> Result<Self> {
let mut xml = Reader::from_reader(reader);
xml.config_mut().trim_text(true);
let mut buf = Vec::with_capacity(8 * 1024);
let mut custom: HashMap<u32, String> = HashMap::new();
let mut fonts: Vec<CellStyle> = Vec::new();
let mut fills: Vec<Option<u32>> = Vec::new();
let mut xfs: Vec<XfInfo> = Vec::new();
let mut dxfs: Vec<CellStyle> = Vec::new();
let mut in_fonts = false;
let mut in_fills = false;
let mut in_cell_xfs = false;
let mut in_dxfs = false;
let mut in_dxf = false;
let mut cur_font = CellStyle::default();
let mut cur_fill: Option<u32> = None;
let mut cur_dxf = CellStyle::default();
loop {
match xml.read_event_into(&mut buf) {
Ok(Event::Eof) => break,
Err(e) => return Err(e.into()),
Ok(Event::Start(e)) => match e.local_name().as_ref() {
b"numFmt" => parse_num_fmt(&e, &mut custom),
b"fonts" => in_fonts = true,
b"fills" => in_fills = true,
b"cellXfs" => in_cell_xfs = true,
b"dxfs" => in_dxfs = true,
b"font" if in_fonts => cur_font = CellStyle::default(),
b"b" if in_fonts => cur_font.bold = true,
b"i" if in_fonts => cur_font.italic = true,
b"color" if in_fonts => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_font.font_color = Some(rgb);
}
}
b"fill" if in_fills => cur_fill = None,
b"fgColor" if in_fills => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_fill = Some(rgb);
}
}
b"xf" if in_cell_xfs => xfs.push(parse_xf(&e)),
b"dxf" if in_dxfs => {
in_dxf = true;
cur_dxf = CellStyle::default();
}
b"b" if in_dxf => cur_dxf.bold = true,
b"i" if in_dxf => cur_dxf.italic = true,
b"color" if in_dxf => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_dxf.font_color = Some(rgb);
}
}
b"fgColor" | b"bgColor" if in_dxf => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_dxf.background = Some(rgb);
}
}
_ => {}
},
Ok(Event::Empty(e)) => match e.local_name().as_ref() {
b"numFmt" => parse_num_fmt(&e, &mut custom),
b"b" if in_fonts => cur_font.bold = true,
b"i" if in_fonts => cur_font.italic = true,
b"color" if in_fonts => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_font.font_color = Some(rgb);
}
}
b"fgColor" if in_fills => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_fill = Some(rgb);
}
}
b"xf" if in_cell_xfs => xfs.push(parse_xf(&e)),
b"font" if in_fonts => fonts.push(CellStyle::default()),
b"fill" if in_fills => fills.push(None),
b"dxf" if in_dxfs => dxfs.push(CellStyle::default()),
b"b" if in_dxf => cur_dxf.bold = true,
b"i" if in_dxf => cur_dxf.italic = true,
b"color" if in_dxf => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_dxf.font_color = Some(rgb);
}
}
b"fgColor" | b"bgColor" if in_dxf => {
if let Some(rgb) = attr(&e, b"rgb").and_then(|v| parse_rgb(&v)) {
cur_dxf.background = Some(rgb);
}
}
_ => {}
},
Ok(Event::End(e)) => match e.local_name().as_ref() {
b"fonts" => in_fonts = false,
b"fills" => in_fills = false,
b"cellXfs" => in_cell_xfs = false,
b"dxfs" => in_dxfs = false,
b"font" if in_fonts => fonts.push(std::mem::take(&mut cur_font)),
b"fill" if in_fills => fills.push(cur_fill.take()),
b"dxf" if in_dxfs => {
dxfs.push(std::mem::take(&mut cur_dxf));
in_dxf = false;
}
_ => {}
},
_ => {}
}
buf.clear();
}
let date_styles = xfs
.iter()
.enumerate()
.filter(|(_, xf)| is_date_format(xf.num_fmt_id, custom.get(&xf.num_fmt_id).map(|s| s.as_str())))
.map(|(i, _)| i as u32)
.collect();
let cell_styles = xfs
.iter()
.map(|xf| {
let mut style = fonts.get(xf.font_id as usize).copied().unwrap_or_default();
style.background = fills.get(xf.fill_id as usize).copied().flatten();
style
})
.collect();
Ok(Self {
date_styles,
cell_styles,
dxfs,
})
}
}
#[derive(Debug, Clone, Copy, Default)]
struct XfInfo {
num_fmt_id: u32,
font_id: u32,
fill_id: u32,
}
fn parse_num_fmt(e: &BytesStart<'_>, custom: &mut HashMap<u32, String>) {
let id = attr(e, b"numFmtId").and_then(|v| v.parse::<u32>().ok());
let code = attr(e, b"formatCode");
if let (Some(id), Some(code)) = (id, code) {
custom.insert(id, code);
}
}
fn parse_xf(e: &BytesStart<'_>) -> XfInfo {
XfInfo {
num_fmt_id: attr(e, b"numFmtId")
.and_then(|v| v.parse().ok())
.unwrap_or(0),
font_id: attr(e, b"fontId").and_then(|v| v.parse().ok()).unwrap_or(0),
fill_id: attr(e, b"fillId").and_then(|v| v.parse().ok()).unwrap_or(0),
}
}
fn attr(e: &BytesStart<'_>, name: &[u8]) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == name)
.map(|a| String::from_utf8_lossy(&a.value).into_owned())
}
fn parse_rgb(raw: &str) -> Option<u32> {
let s = raw.trim().trim_start_matches('#');
let hex = if s.len() == 8 {
&s[2..]
} else if s.len() == 6 {
s
} else {
return None;
};
u32::from_str_radix(hex, 16).ok()
}
const BUILTIN_DATE_FORMATS: &[u32] = &[
14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 50, 51,
52, 53, 54, 55, 56, 57, 58,
];
pub fn is_date_format(num_fmt_id: u32, code: Option<&str>) -> bool {
match code {
Some(code) => is_date_code(code),
None => BUILTIN_DATE_FORMATS.contains(&num_fmt_id),
}
}
pub fn is_date_code(code: &str) -> bool {
let mut cleaned = String::with_capacity(code.len());
let mut in_quote = false;
let mut escaped = false;
for c in code.chars() {
if escaped {
escaped = false;
continue;
}
match c {
'\\' => escaped = true,
'"' => in_quote = !in_quote,
'[' => in_quote = true,
']' => in_quote = false,
_ if in_quote => {}
_ => cleaned.push(c.to_ascii_lowercase()),
}
}
let first = cleaned.split(';').next().unwrap_or("").trim().to_string();
if first.is_empty() {
return false;
}
if first.contains('y') || first.contains('d') || first.contains('h') || first.contains('s') {
return true;
}
first.contains('m') && (first.contains('/') || first.contains('-') || first.contains(':'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_date_codes() {
assert!(is_date_code("yyyy-mm-dd"));
assert!(is_date_code("yyyy\"年\"m\"月\"d\"日\""));
assert!(is_date_code("h:mm:ss"));
assert!(is_date_code("mm:ss"));
assert!(!is_date_code("#,##0.00"));
assert!(!is_date_code("@"));
assert!(!is_date_code("General"));
assert!(!is_date_code("0.00%"));
assert!(is_date_format(14, None));
assert!(!is_date_format(2, None));
assert!(is_date_format(2, Some("yyyy/mm/dd")));
}
#[test]
fn test_parse_rgb() {
assert_eq!(parse_rgb("FFFF0000"), Some(0xFF0000));
assert_eq!(parse_rgb("00FF00"), Some(0x00FF00));
assert_eq!(parse_rgb("#123456"), Some(0x123456));
assert_eq!(parse_rgb("xyz"), None);
}
#[test]
fn test_parse_styles_fonts_fills() {
let xml = r#"<?xml version="1.0"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<fonts count="2">
<font><sz val="11"/><color theme="1"/><name val="Calibri"/></font>
<font><b/><i/><color rgb="FFFF0000"/><name val="Calibri"/></font>
</fonts>
<fills count="2">
<fill><patternFill patternType="none"/></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFFFFF00"/></patternFill></fill>
</fills>
<cellXfs count="2">
<xf numFmtId="0" fontId="0" fillId="0"/>
<xf numFmtId="0" fontId="1" fillId="1"/>
</cellXfs>
</styleSheet>"#;
let styles = Styles::parse(xml.as_bytes()).unwrap();
assert_eq!(styles.cell_style(0), CellStyle::default());
let s1 = styles.cell_style(1);
assert!(s1.bold && s1.italic);
assert_eq!(s1.font_color, Some(0xFF0000));
assert_eq!(s1.background, Some(0xFFFF00));
assert_eq!(styles.cell_style(99), CellStyle::default());
}
#[test]
fn test_parse_dxfs() {
let xml = r#"<?xml version="1.0"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<dxfs count="2">
<dxf><font><color rgb="FF9C0006"/></font><fill><patternFill><bgColor rgb="FFFFC7CE"/></patternFill></fill></dxf>
<dxf><font><b/><color rgb="FF006100"/></font></dxf>
</dxfs>
</styleSheet>"#;
let styles = Styles::parse(xml.as_bytes()).unwrap();
let d0 = styles.dxf_style(0);
assert_eq!(d0.font_color, Some(0x9C0006));
assert_eq!(d0.background, Some(0xFFC7CE));
let d1 = styles.dxf_style(1);
assert!(d1.bold);
assert_eq!(d1.font_color, Some(0x006100));
assert_eq!(styles.dxf_style(9), CellStyle::default(), "越界安全");
}
}