fast-excel 1.0.0

通用 Excel 导入导出工具:流式读写(百万级)、动态表头适配、多 sheet、单元格图片、批量落库(纯 Rust,对标 EasyExcel)
Documentation
//! `xl/styles.xml` 解析:日期格式判断 + 单元格样式(字体颜色 / 底色 / 加粗 / 斜体)
//!
//! Excel 把日期存成数字(序列号)+ 单元格样式,所以"这一列是不是日期"必须靠
//! 样式里的 `numFmtId` / `formatCode` 判断,否则日期会变成 `45293` 这种数字。
//!
//! 同时解析 `fonts` / `fills` / `cellXfs`,让业务能按"底色 / 字体颜色"做判断
//! (例如黄色底 = 待确认),通过 [`crate::ExcelReader::styles`] 或
//! [`crate::RowData::cell_style`] 取用。

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,
    /// 字体颜色(0xRRGGBB)
    pub font_color: Option<u32>,
    /// 单元格背景色(0xRRGGBB)
    pub background: Option<u32>,
}

/// 单元格样式表
#[derive(Debug, Default)]
pub struct Styles {
    /// 日期样式的 `cellXfs` 下标
    date_styles: HashSet<u32>,
    /// 每个 `cellXfs` 下标的样式(按下标对齐,O(1) 查询)
    cell_styles: Vec<CellStyle>,
    /// 差异格式(`dxfs`,条件格式 `dxfId` 用)
    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()
    }

    /// 取差异格式(条件格式 `dxfId` → 样式);越界 / 未知返回默认样式
    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,
        })
    }
}

/// `cellXfs` 里一个 `xf` 引用
#[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())
}

/// `"FFFF0000"` / `"FF0000"` → `0xFF0000`(取后 6 位;非法返回 `None`)
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()
}

/// 内置日期格式 ID(ECMA-376 预定义)
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,
];

/// 判断 `numFmtId` + 自定义格式串是否为日期/时间
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;
    }
    // 只有 m 时(可能是分钟/月份,也可能是 "0.00" 里的字母)需要配合分隔符
    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(), "越界安全");
    }
}