xlsx-rs2 0.1.0

Rust 版本的 Excel .xlsx 读写库,基于 ooxml-core,对标 python-openpyxl
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! 工作簿(`Workbook`):xlsx-rs 的入口类型,对应一个 `.xlsx` 文件。
//!
//! # OOXML 与本实现的对应
//!
//! | SpreadsheetML / OPC | 本模块 |
//! |---------------------|--------|
//! | `.xlsx` 文件(zip 包) | [`Workbook`] |
//! | `xl/workbook.xml` (`<workbook>` 根元素) | [`Workbook`] 的 sheets 列表元数据 |
//! | `xl/sharedStrings.xml` | [`Workbook::shared_strings`] |
//! | `xl/worksheets/sheetN.xml` | [`Worksheet`] 序列(每张表一个 part) |
//! | `[Content_Types].xml` | 由 [`OpcPackage`] 管理 |
//! | `/_rels/.rels` / `xl/_rels/workbook.xml.rels` | 由 [`OpcPackage`] 管理 |
//!
//! # 三层架构位置
//!
//! `Workbook` 是高阶 API,位于 OPC 层之上:
//! - **保存**:`Workbook::to_opc_package()` 把 `sheets` + `shared_strings` 序列化为
//!   若干 `Part` 注入 [`OpcPackage`],再由 `OpcPackage::save()` 写出 zip;
//! - **加载**:`OpcPackage::load()` 解压 zip 得到 `Part` 集合,
//!   `Workbook::from_opc()` 反序列化为 `sheets` + `shared_strings`。
//!
//! # XLSX 包结构
//!
//! ```text
//! [Content_Types].xml
//! _rels/.rels                              ← 指向 xl/workbook.xml (rId1)
//! xl/workbook.xml                          ← <workbook><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/>...</sheets></workbook>
//! xl/_rels/workbook.xml.rels               ← 指向 worksheets/sheet1.xml + sharedStrings.xml
//! xl/worksheets/sheet1.xml                 ← <worksheet><sheetData>...</sheetData></worksheet>
//! xl/worksheets/sheet2.xml                 ← (如有更多 sheet)
//! xl/sharedStrings.xml                     ← <sst>...</sst>
//! ```

use std::path::Path;

use ooxml_core::opc::{self, OpcPackage, Part, PartName, RelType, Relationship, Relationships};

use crate::error::{Error, Result};
use crate::shared_strings::SharedStringsTable;
use crate::worksheet::Worksheet;

/// SpreadsheetML 命名空间。
const NS_SPREADSHEETML: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
/// 关系命名空间。
const NS_RELATIONSHIPS: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/// XLSX workbook.xml Content-Type。
const CT_WORKBOOK: &str =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
/// XLSX worksheet.xml Content-Type。
const CT_WORKSHEET: &str =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
/// XLSX sharedStrings.xml Content-Type。
const CT_SHARED_STRINGS: &str =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";

/// 一个 Excel 工作簿(对应一个 `.xlsx` 文件)。
#[derive(Debug, Clone)]
pub struct Workbook {
    /// 所有工作表(顺序对应 Excel 中的 Tab 顺序)。
    sheets: Vec<Worksheet>,
    /// 共享字符串表(所有 sheet 共享)。
    shared_strings: SharedStringsTable,
}

impl Default for Workbook {
    fn default() -> Self {
        Self::new()
    }
}

impl Workbook {
    /// 构造一个新工作簿,含一张名为 `"Sheet1"` 的空表(与 Excel 默认行为一致)。
    pub fn new() -> Self {
        let mut wb = Workbook {
            sheets: Vec::new(),
            shared_strings: SharedStringsTable::new(),
        };
        wb.sheets.push(Worksheet::new("Sheet1"));
        wb
    }

    /// 构造一个不含任何 sheet 的工作簿(调用方需自行 `add_sheet`)。
    pub fn with_no_sheets() -> Self {
        Workbook {
            sheets: Vec::new(),
            shared_strings: SharedStringsTable::new(),
        }
    }

    /// 添加一张工作表,返回其索引。
    ///
    /// # 错误
    /// - [`Error::InvalidSheetName`]:名称为空、含 `[ ] : * ? / \` 等非法字符、长度 > 31。
    pub fn add_sheet(&mut self, name: &str) -> Result<usize> {
        validate_sheet_name(name)?;
        if self.sheets.iter().any(|s| s.name() == name) {
            return Err(Error::InvalidSheetName(format!(
                "duplicate sheet name: '{}'",
                name
            )));
        }
        self.sheets.push(Worksheet::new(name));
        Ok(self.sheets.len() - 1)
    }

    /// 移除指定索引的工作表,返回被移除的 Worksheet。
    ///
    /// # 错误
    /// - [`Error::IndexOutOfRange`]:索引越界。
    pub fn remove_sheet(&mut self, index: usize) -> Result<Worksheet> {
        if index >= self.sheets.len() {
            return Err(Error::IndexOutOfRange(index));
        }
        Ok(self.sheets.remove(index))
    }

    /// 工作表数量。
    pub fn sheet_count(&self) -> usize {
        self.sheets.len()
    }

    /// 按索引取工作表不可变引用。
    pub fn get_sheet(&self, index: usize) -> Option<&Worksheet> {
        self.sheets.get(index)
    }

    /// 按索引取工作表可变引用。
    pub fn get_sheet_mut(&mut self, index: usize) -> Option<&mut Worksheet> {
        self.sheets.get_mut(index)
    }

    /// 按名称查找工作表索引。
    pub fn get_sheet_index_by_name(&self, name: &str) -> Option<usize> {
        self.sheets.iter().position(|s| s.name() == name)
    }

    /// 按名称取工作表不可变引用。
    pub fn get_sheet_by_name(&self, name: &str) -> Option<&Worksheet> {
        self.get_sheet_index_by_name(name)
            .and_then(|i| self.get_sheet(i))
    }

    /// 按名称取工作表可变引用。
    pub fn get_sheet_by_name_mut(&mut self, name: &str) -> Option<&mut Worksheet> {
        if let Some(i) = self.get_sheet_index_by_name(name) {
            return self.get_sheet_mut(i);
        }
        None
    }

    /// 迭代所有工作表。
    pub fn iter_sheets(&self) -> impl Iterator<Item = &Worksheet> {
        self.sheets.iter()
    }

    /// 迭代所有工作表(可变)。
    pub fn iter_sheets_mut(&mut self) -> impl Iterator<Item = &mut Worksheet> {
        self.sheets.iter_mut()
    }

    /// 共享字符串表(不可变)。
    pub fn shared_strings(&self) -> &SharedStringsTable {
        &self.shared_strings
    }

    /// 共享字符串表(可变)。
    pub fn shared_strings_mut(&mut self) -> &mut SharedStringsTable {
        &mut self.shared_strings
    }

    /// 保存到 `.xlsx` 文件。
    ///
    /// 内部流程:`to_opc_package()` → `OpcPackage::save()`。
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let pkg = self.to_opc_package();
        Ok(pkg.save(path)?)
    }

    /// 从 `.xlsx` 文件加载。
    ///
    /// 内部流程:`OpcPackage::load()` → `Workbook::from_opc()`。
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let pkg = OpcPackage::load(path.as_ref())?;
        Self::from_opc(pkg)
    }

    /// 序列化为字节(内存中的 `.xlsx` zip 字节流)。
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let pkg = self.to_opc_package();
        Ok(pkg.to_bytes()?)
    }

    /// 从字节加载(内存中的 `.xlsx` zip 字节流)。
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        use std::io::{Cursor, Read};
        let cursor = Cursor::new(bytes);
        let mut zip = zip::ZipArchive::new(cursor)?;
        let mut pkg = OpcPackage::new();
        // 1) [Content_Types].xml
        let mut ct_xml = String::new();
        zip.by_name("[Content_Types].xml")?
            .read_to_string(&mut ct_xml)?;
        pkg.content_types = parse_content_types(&ct_xml)?;
        // 2) 所有 part
        for i in 0..zip.len() {
            let mut entry = zip.by_index(i)?;
            let name = entry.name().to_string();
            if name == "[Content_Types].xml" || entry.is_dir() {
                continue;
            }
            let mut blob = Vec::with_capacity(entry.size() as usize);
            entry.read_to_end(&mut blob)?;
            let ct = if name.ends_with(".rels") {
                opc::ct::RELATIONSHIPS.to_string()
            } else {
                opc::package::derive_content_type(&pkg.content_types, &format!("/{}", name))
            };
            let partname = format!("/{}", name);
            let part = Part::new(PartName::from_unchecked(partname), ct, blob);
            pkg.parts.insert(part.partname.as_str().to_string(), part);
        }
        Self::from_opc(pkg)
    }

    /// 把 Workbook 转换为 OpcPackage(注入所有 part + ContentTypes override)。
    ///
    /// # 注入的 part 列表
    /// - `/xl/workbook.xml`:sheets 元数据
    /// - `/xl/_rels/workbook.xml.rels`:指向 worksheets + sharedStrings
    /// - `/xl/worksheets/sheetN.xml`:每张表一个
    /// - `/xl/sharedStrings.xml`:共享字符串(仅当 SST 非空)
    /// - `/_rels/.rels`:根关系,指向 `xl/workbook.xml`
    pub fn to_opc_package(&self) -> OpcPackage {
        let mut pkg = OpcPackage::new();

        // 1) 重新构造一个干净的 SST:避免多次 round-trip 时累积残留
        let mut fresh_sst = SharedStringsTable::new();
        // 2) 写出 worksheets 并构造 workbook.xml + workbook.xml.rels
        let mut workbook_xml = String::with_capacity(256);
        workbook_xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n");
        workbook_xml.push_str(&format!(
            "<workbook xmlns=\"{}\" xmlns:r=\"{}\">",
            NS_SPREADSHEETML, NS_RELATIONSHIPS
        ));
        workbook_xml.push_str("<sheets>");

        let mut wb_rels = Relationships::new();
        let mut rid_counter: u32 = 0;

        for (idx, sheet) in self.sheets.iter().enumerate() {
            let rid = format!("rId{}", idx + 1);
            rid_counter = (idx + 1) as u32;

            // sheetN.xml
            let sheet_partname = format!("/xl/worksheets/sheet{}.xml", idx + 1);
            let sheet_xml = sheet.to_xml(&mut fresh_sst);
            pkg.put_part(Part::new(
                PartName::from_unchecked(sheet_partname.clone()),
                CT_WORKSHEET.to_string(),
                sheet_xml.into_bytes(),
            ));

            // workbook.xml 的 <sheet> 元素
            workbook_xml.push_str(&format!(
                "<sheet name=\"{}\" sheetId=\"{}\" r:id=\"{}\"/>",
                xml_escape_attr(sheet.name()),
                idx + 1,
                rid
            ));

            // workbook.xml.rels
            wb_rels
                .add(Relationship::internal_str(
                    rid.clone(),
                    RelType::Other(
                        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
                            .to_string(),
                    ),
                    format!("worksheets/sheet{}.xml", idx + 1),
                ))
                .ok();
        }

        workbook_xml.push_str("</sheets>");
        workbook_xml.push_str("</workbook>");

        // 3) sharedStrings.xml(仅当非空)
        if !fresh_sst.is_empty() {
            rid_counter += 1;
            let sst_rid = format!("rId{}", rid_counter);
            let sst_xml = fresh_sst.to_xml();
            pkg.put_part(Part::new(
                PartName::from_unchecked("/xl/sharedStrings.xml".to_string()),
                CT_SHARED_STRINGS.to_string(),
                sst_xml.into_bytes(),
            ));
            wb_rels
                .add(Relationship::internal_str(
                    sst_rid,
                    RelType::Other(
                        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"
                            .to_string(),
                    ),
                    "sharedStrings.xml",
                ))
                .ok();
        }

        // 4) workbook.xml
        pkg.put_part(Part::new(
            PartName::from_unchecked("/xl/workbook.xml".to_string()),
            CT_WORKBOOK.to_string(),
            workbook_xml.into_bytes(),
        ));

        // 5) workbook.xml.rels
        pkg.put_part(Part::new(
            PartName::from_unchecked("/xl/_rels/workbook.xml.rels".to_string()),
            opc::ct::RELATIONSHIPS.to_string(),
            wb_rels.to_xml().into_bytes(),
        ));

        // 6) 根 .rels:指向 xl/workbook.xml
        let mut root_rels = Relationships::new();
        root_rels
            .add(Relationship::internal_str(
                "rId1",
                RelType::OfficeDocument,
                "xl/workbook.xml",
            ))
            .ok();
        pkg.put_part(Part::new(
            PartName::from_unchecked("/_rels/.rels".to_string()),
            opc::ct::RELATIONSHIPS.to_string(),
            root_rels.to_xml().into_bytes(),
        ));

        // 替换 workbook 的 shared_strings 为重新构造的版本
        // (保证多次 to_opc_package 调用结果稳定)
        // 注意:这里通过 unwrap 安全:pkg 是新建的,parts 一定包含 sharedStrings.xml(若非空)
        // 但 shared_strings 字段在 self 上不变,需要外部调用方注意。

        pkg
    }

    /// 从 OpcPackage 反序列化为 Workbook。
    ///
    /// # 解析流程
    /// 1. 读 `/xl/sharedStrings.xml`(如存在)→ `SharedStringsTable`;
    /// 2. 读 `/xl/workbook.xml` → sheet 名称顺序 + r:id 映射;
    /// 3. 读 `/xl/_rels/workbook.xml.rels` → r:id → sheetN.xml partname 映射;
    /// 4. 按 workbook.xml 中的顺序逐个解析 `xl/worksheets/sheetN.xml` → `Worksheet`。
    pub fn from_opc(pkg: OpcPackage) -> Result<Self> {
        // 1) SharedStrings
        let mut sst = SharedStringsTable::new();
        if let Some(part) = pkg.get_part("/xl/sharedStrings.xml") {
            let xml = part
                .blob_text()
                .ok_or_else(|| Error::Schema("sharedStrings.xml is not UTF-8".to_string()))?;
            sst = SharedStringsTable::from_xml(&xml)?;
        }

        // 2) workbook.xml
        let wb_part = pkg
            .get_part("/xl/workbook.xml")
            .ok_or_else(|| Error::Schema("missing /xl/workbook.xml".to_string()))?;
        let wb_xml = wb_part
            .blob_text()
            .ok_or_else(|| Error::Schema("workbook.xml is not UTF-8".to_string()))?;
        let sheet_meta = parse_workbook_xml(&wb_xml)?;

        // 3) workbook.xml.rels
        let mut rid_to_target: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        if let Some(rels_part) = pkg.get_part("/xl/_rels/workbook.xml.rels") {
            let rels_xml = rels_part
                .blob_text()
                .ok_or_else(|| Error::Schema("workbook.xml.rels is not UTF-8".to_string()))?;
            let rels = Relationships::from_xml(&rels_xml)?;
            for r in rels.iter() {
                rid_to_target.insert(r.id.clone(), r.target.as_str().to_string());
            }
        }

        // 4) 逐个解析 worksheet
        let mut sheets = Vec::with_capacity(sheet_meta.len());
        for meta in &sheet_meta {
            let target = rid_to_target.get(&meta.rid).ok_or_else(|| {
                Error::Schema(format!("workbook.xml.rels missing rid '{}'", meta.rid))
            })?;
            // target 是相对路径,如 "worksheets/sheet1.xml"
            let partname = format!("/xl/{}", target);
            let part = pkg
                .get_part(&partname)
                .ok_or_else(|| Error::Schema(format!("missing worksheet part: {}", partname)))?;
            let xml = part
                .blob_text()
                .ok_or_else(|| Error::Schema(format!("{} is not UTF-8", partname)))?;
            let mut ws = Worksheet::from_xml(&xml, &sst)?;
            // worksheet.xml 不含 sheet 名称,名称来自 workbook.xml
            ws.set_name(&meta.name);
            sheets.push(ws);
        }

        Ok(Workbook {
            sheets,
            shared_strings: sst,
        })
    }
}

/// workbook.xml 解析结果:sheet 列表的元数据(名称 + r:id)。
struct SheetMeta {
    name: String,
    rid: String,
}

/// 解析 `xl/workbook.xml` 提取 `<sheet>` 列表。
///
/// 仅提取 `name` 与 `r:id` 属性,`sheetId` 暂不使用(OOXML 中 sheetId 用于 SDK 内部,
/// 文件内的 sheet 顺序由 `<sheets>` 子元素顺序决定)。
fn parse_workbook_xml(xml: &str) -> Result<Vec<SheetMeta>> {
    use quick_xml::events::Event;
    use quick_xml::reader::Reader;

    let mut metas = Vec::new();
    let mut rd = Reader::from_str(xml);
    // 不开启 trim_text:见 shared_strings.rs 同样注释。
    let mut buf = Vec::new();

    loop {
        match rd.read_event_into(&mut buf) {
            Ok(Event::Empty(e)) | Ok(Event::Start(e)) => {
                if e.name().as_ref() == b"sheet" {
                    let mut name = None;
                    let mut rid = None;
                    for attr in e.attributes().flatten() {
                        let v = attr
                            .normalized_value(quick_xml::XmlVersion::Implicit1_0)
                            .ok()
                            .map(|v| v.to_string())
                            .unwrap_or_default();
                        match attr.key.as_ref() {
                            b"name" => name = Some(v),
                            b"id" => rid = Some(v), // r:id 会被解析为 id(去掉 namespace 前缀)
                            _ => {}
                        }
                    }
                    // r:id 属性的 key 在 quick-xml 中带命名空间前缀,需特殊处理
                    for attr in e.attributes().flatten() {
                        let key_str = std::str::from_utf8(attr.key.as_ref()).unwrap_or("");
                        if key_str.ends_with(":id") {
                            rid = Some(
                                attr.normalized_value(quick_xml::XmlVersion::Implicit1_0)
                                    .ok()
                                    .map(|v| v.to_string())
                                    .unwrap_or_default(),
                            );
                        }
                    }
                    let (Some(name), Some(rid)) = (name, rid) else {
                        return Err(Error::Schema(
                            "workbook.xml <sheet> missing name or r:id".to_string(),
                        ));
                    };
                    metas.push(SheetMeta { name, rid });
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(Error::Xml(format!("workbook.xml parse: {e}"))),
            _ => {}
        }
        buf.clear();
    }
    Ok(metas)
}

/// 极简解析 `[Content_Types].xml`,复用 ooxml-core 的实现。
fn parse_content_types(xml: &str) -> Result<opc::ContentTypes> {
    // 直接调用 ooxml-core 的公开函数
    let ct = opc::package::parse_content_types_public(xml)?;
    Ok(ct)
}

/// 校验工作表名称(OOXML 规则)。
///
/// # 规则
/// - 不能为空;
/// - 长度 1-31 字符;
/// - 不能含 `[ ] : * ? / \` 任一字符;
/// - 不能以单引号 `'` 开头或结尾。
fn validate_sheet_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::InvalidSheetName(
            "sheet name cannot be empty".to_string(),
        ));
    }
    let char_count = name.chars().count();
    if char_count > 31 {
        return Err(Error::InvalidSheetName(format!(
            "sheet name too long: {} chars (max 31)",
            char_count
        )));
    }
    for c in name.chars() {
        if matches!(c, '[' | ']' | ':' | '*' | '?' | '/' | '\\') {
            return Err(Error::InvalidSheetName(format!(
                "sheet name contains illegal char '{}': '{}'",
                c, name
            )));
        }
    }
    if name.starts_with('\'') || name.ends_with('\'') {
        return Err(Error::InvalidSheetName(format!(
            "sheet name cannot start or end with apostrophe: '{}'",
            name
        )));
    }
    Ok(())
}

/// XML 属性值转义(覆盖 `& < > "`)。
fn xml_escape_attr(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CellValue;

    #[test]
    fn new_has_default_sheet() {
        let wb = Workbook::new();
        assert_eq!(wb.sheet_count(), 1);
        assert_eq!(wb.get_sheet(0).unwrap().name(), "Sheet1");
    }

    #[test]
    fn add_sheet_increments_count() {
        let mut wb = Workbook::new();
        let idx = wb.add_sheet("Data").unwrap();
        assert_eq!(idx, 1);
        assert_eq!(wb.sheet_count(), 2);
        assert_eq!(wb.get_sheet(1).unwrap().name(), "Data");
    }

    #[test]
    fn add_sheet_duplicate_name_errors() {
        let mut wb = Workbook::new();
        assert!(wb.add_sheet("Sheet1").is_err());
    }

    #[test]
    fn add_sheet_invalid_name_errors() {
        let mut wb = Workbook::new();
        assert!(wb.add_sheet("").is_err());
        assert!(wb.add_sheet("a/b").is_err());
        assert!(wb.add_sheet("a:b").is_err());
        assert!(wb.add_sheet("a*b").is_err());
        assert!(wb.add_sheet("a?b").is_err());
        assert!(wb.add_sheet("a[b]b").is_err());
        assert!(wb.add_sheet("a\\b").is_err());
        assert!(wb.add_sheet("'quoted'").is_err());
        // 32 字符名称
        let long_name = "a".repeat(32);
        assert!(wb.add_sheet(&long_name).is_err());
    }

    #[test]
    fn add_sheet_max_length_ok() {
        let mut wb = Workbook::new();
        let name_31 = "a".repeat(31);
        assert!(wb.add_sheet(&name_31).is_ok());
    }

    #[test]
    fn remove_sheet() {
        let mut wb = Workbook::new();
        wb.add_sheet("Data").unwrap();
        let removed = wb.remove_sheet(0).unwrap();
        assert_eq!(removed.name(), "Sheet1");
        assert_eq!(wb.sheet_count(), 1);
        assert_eq!(wb.get_sheet(0).unwrap().name(), "Data");
    }

    #[test]
    fn remove_sheet_out_of_range() {
        let mut wb = Workbook::new();
        assert!(wb.remove_sheet(5).is_err());
    }

    #[test]
    fn get_sheet_by_name() {
        let mut wb = Workbook::new();
        wb.add_sheet("Data").unwrap();
        assert!(wb.get_sheet_by_name("Sheet1").is_some());
        assert!(wb.get_sheet_by_name("Data").is_some());
        assert!(wb.get_sheet_by_name("NonExist").is_none());
        assert_eq!(wb.get_sheet_index_by_name("Data"), Some(1));
    }

    #[test]
    fn iter_sheets() {
        let mut wb = Workbook::new();
        wb.add_sheet("Data").unwrap();
        let names: Vec<&str> = wb.iter_sheets().map(|s| s.name()).collect();
        assert_eq!(names, vec!["Sheet1", "Data"]);
    }

    #[test]
    fn set_cell_through_workbook() {
        let mut wb = Workbook::new();
        let sheet = wb.get_sheet_mut(0).unwrap();
        sheet.set_cell("A1", CellValue::Number(42.0)).unwrap();
        assert_eq!(
            sheet.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::Number(42.0)
        );
    }

    #[test]
    fn to_opc_package_has_required_parts() {
        let mut wb = Workbook::new();
        {
            let s = wb.get_sheet_mut(0).unwrap();
            s.set_cell("A1", CellValue::Number(1.0)).unwrap();
            s.set_cell("A2", CellValue::String("Hello".to_string()))
                .unwrap();
        }
        let pkg = wb.to_opc_package();

        // 必须存在的 part
        assert!(pkg.get_part("/xl/workbook.xml").is_some());
        assert!(pkg.get_part("/xl/worksheets/sheet1.xml").is_some());
        assert!(pkg.get_part("/xl/sharedStrings.xml").is_some());
        assert!(pkg.get_part("/xl/_rels/workbook.xml.rels").is_some());
        assert!(pkg.get_part("/_rels/.rels").is_some());

        // workbook.xml Content-Type override
        assert!(pkg.content_types.has_override("/xl/workbook.xml"));
        assert!(pkg.content_types.has_override("/xl/worksheets/sheet1.xml"));
        assert!(pkg.content_types.has_override("/xl/sharedStrings.xml"));
    }

    #[test]
    fn to_opc_package_no_shared_strings_when_empty() {
        let wb = Workbook::new();
        let pkg = wb.to_opc_package();
        // 没有字符串时不应写出 sharedStrings.xml
        assert!(pkg.get_part("/xl/sharedStrings.xml").is_none());
    }

    #[test]
    fn round_trip_basic() {
        let mut wb = Workbook::new();
        {
            let s = wb.get_sheet_mut(0).unwrap();
            s.set_cell("A1", CellValue::Number(1.0)).unwrap();
            s.set_cell("B1", CellValue::Number(2.0)).unwrap();
            s.set_cell("A2", CellValue::String("Hello".to_string()))
                .unwrap();
            s.set_cell("B2", CellValue::String("World".to_string()))
                .unwrap();
            s.set_cell("C3", CellValue::Boolean(true)).unwrap();
        }
        let bytes = wb.to_bytes().unwrap();
        let wb2 = Workbook::from_bytes(&bytes).unwrap();

        assert_eq!(wb2.sheet_count(), 1);
        let s2 = wb2.get_sheet(0).unwrap();
        assert_eq!(
            s2.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::Number(1.0)
        );
        assert_eq!(
            s2.get_cell("A2").unwrap().unwrap().value(),
            &CellValue::String("Hello".to_string())
        );
        assert_eq!(
            s2.get_cell("B2").unwrap().unwrap().value(),
            &CellValue::String("World".to_string())
        );
        assert_eq!(
            s2.get_cell("C3").unwrap().unwrap().value(),
            &CellValue::Boolean(true)
        );
    }

    #[test]
    fn round_trip_multiple_sheets() {
        let mut wb = Workbook::new();
        wb.add_sheet("Data").unwrap();
        {
            let s0 = wb.get_sheet_mut(0).unwrap();
            s0.set_cell("A1", CellValue::String("Sheet1 content".to_string()))
                .unwrap();
        }
        {
            let s1 = wb.get_sheet_mut(1).unwrap();
            s1.set_cell("A1", CellValue::Number(100.0)).unwrap();
            s1.set_cell("B2", CellValue::String("Data content".to_string()))
                .unwrap();
        }
        let bytes = wb.to_bytes().unwrap();
        let wb2 = Workbook::from_bytes(&bytes).unwrap();

        assert_eq!(wb2.sheet_count(), 2);
        assert_eq!(wb2.get_sheet(0).unwrap().name(), "Sheet1");
        assert_eq!(wb2.get_sheet(1).unwrap().name(), "Data");
        assert_eq!(
            wb2.get_sheet(0)
                .unwrap()
                .get_cell("A1")
                .unwrap()
                .unwrap()
                .value(),
            &CellValue::String("Sheet1 content".to_string())
        );
        assert_eq!(
            wb2.get_sheet(1)
                .unwrap()
                .get_cell("B2")
                .unwrap()
                .unwrap()
                .value(),
            &CellValue::String("Data content".to_string())
        );
    }

    #[test]
    fn round_trip_special_chars_in_string() {
        let mut wb = Workbook::new();
        let text = "Hello <World> & \"Friends\"".to_string();
        {
            let s = wb.get_sheet_mut(0).unwrap();
            s.set_cell("A1", CellValue::String(text.clone())).unwrap();
        }
        let bytes = wb.to_bytes().unwrap();
        let wb2 = Workbook::from_bytes(&bytes).unwrap();
        assert_eq!(
            wb2.get_sheet(0)
                .unwrap()
                .get_cell("A1")
                .unwrap()
                .unwrap()
                .value(),
            &CellValue::String(text)
        );
    }

    #[test]
    fn round_trip_save_load_file() {
        let mut wb = Workbook::new();
        {
            let s = wb.get_sheet_mut(0).unwrap();
            s.set_cell("A1", CellValue::Number(42.0)).unwrap();
            s.set_cell("A2", CellValue::String("File test".to_string()))
                .unwrap();
        }
        let path = std::env::temp_dir().join("xlsx_rs_round_trip_test.xlsx");
        wb.save(&path).unwrap();
        let wb2 = Workbook::load(&path).unwrap();
        let _ = std::fs::remove_file(&path);

        assert_eq!(wb2.sheet_count(), 1);
        let s2 = wb2.get_sheet(0).unwrap();
        assert_eq!(
            s2.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::Number(42.0)
        );
        assert_eq!(
            s2.get_cell("A2").unwrap().unwrap().value(),
            &CellValue::String("File test".to_string())
        );
    }

    #[test]
    fn validate_sheet_name_rules() {
        assert!(validate_sheet_name("OK").is_ok());
        assert!(validate_sheet_name("Sheet 1").is_ok());
        assert!(validate_sheet_name("中文表").is_ok());
        assert!(validate_sheet_name("").is_err());
        assert!(validate_sheet_name("a[b").is_err());
        assert!(validate_sheet_name(&"x".repeat(32)).is_err());
        assert!(validate_sheet_name(&"x".repeat(31)).is_ok());
    }
}