Skip to main content

fast_excel/read/
shared_strings.rs

1//! `xl/sharedStrings.xml` 解析(字符串池)
2//!
3//! 池子必须整体常驻(一个字符串的索引可以出现在任意位置),但**只装字符串本身**,
4//! 一个 100 万行 x 10 列的文件池子通常是几十 MB,属于可控量级。
5//! 需要更省内存时,写出侧请用 inline string 或数字列。
6
7use std::io::BufRead;
8
9use quick_xml::Reader;
10use quick_xml::events::{BytesText, Event};
11
12use crate::error::Result;
13
14/// 共享字符串池
15#[derive(Debug, Default)]
16pub struct SharedStrings {
17    items: Vec<String>,
18}
19
20impl SharedStrings {
21    pub fn empty() -> Self {
22        Self { items: Vec::new() }
23    }
24
25    pub fn len(&self) -> usize {
26        self.items.len()
27    }
28
29    pub fn is_empty(&self) -> bool {
30        self.items.is_empty()
31    }
32
33    /// 按索引取字符串
34    pub fn get(&self, index: usize) -> Option<&str> {
35        self.items.get(index).map(|s| s.as_str())
36    }
37
38    pub fn push(&mut self, s: String) {
39        self.items.push(s);
40    }
41
42    /// 流式解析:只保留文本,富文本(`<r><t>`)拼接成一段,拼音(`<rPh>`)丢弃
43    pub fn parse<R: BufRead>(reader: R) -> Result<Self> {
44        let mut xml = Reader::from_reader(reader);
45        xml.config_mut().trim_text(false);
46        let mut buf = Vec::with_capacity(8 * 1024);
47        let mut items: Vec<String> = Vec::new();
48        let mut cur = String::new();
49        let mut in_si = false;
50        let mut in_rph = false;
51        let mut in_t = false;
52
53        loop {
54            match xml.read_event_into(&mut buf) {
55                Ok(Event::Eof) => break,
56                Err(e) => return Err(e.into()),
57                Ok(Event::Start(e)) => match e.local_name().as_ref() {
58                    b"si" => {
59                        in_si = true;
60                        cur.clear();
61                    }
62                    b"rPh" => in_rph = true,
63                    b"t" => in_t = true,
64                    _ => {}
65                },
66                Ok(Event::End(e)) => match e.local_name().as_ref() {
67                    b"si" => {
68                        in_si = false;
69                        items.push(std::mem::take(&mut cur));
70                    }
71                    b"rPh" => in_rph = false,
72                    b"t" => in_t = false,
73                    _ => {}
74                },
75                Ok(Event::Text(t)) if in_t && !in_rph && in_si => {
76                    cur.push_str(&decode_text(&t));
77                }
78                Ok(Event::CData(t)) if in_t && !in_rph && in_si => {
79                    cur.push_str(&String::from_utf8_lossy(t.as_ref()));
80                }
81                _ => {}
82            }
83            buf.clear();
84        }
85        Ok(Self { items })
86    }
87}
88
89/// XML 文本解码(实体转义 → 原文)
90pub(crate) fn decode_text(t: &BytesText<'_>) -> String {
91    match t.unescape() {
92        Ok(c) => c.into_owned(),
93        Err(e) => {
94            log::warn!("Excel 文本实体解码失败,按原样保留:{e}");
95            String::from_utf8_lossy(t.as_ref()).into_owned()
96        }
97    }
98}