fast_excel/read/
shared_strings.rs1use std::io::BufRead;
8
9use quick_xml::Reader;
10use quick_xml::events::{BytesText, Event};
11
12use crate::error::Result;
13
14#[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 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 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
89pub(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}