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
//! 工作表(`Worksheet`):对应 SpreadsheetML 的 `<worksheet>` 元素。
//!
//! # OOXML 与本实现的对应
//!
//! | SpreadsheetML | 本模块 |
//! |---------------|--------|
//! | `<worksheet>` 根元素 | [`Worksheet`] |
//! | `<dimension ref="A1:C3"/>` | [`Worksheet::dimension`] 自动计算 |
//! | `<sheetData>` | [`Worksheet::iter_rows`] 内部存储 |
//! | `<row r="1">` | `BTreeMap<u32 row, BTreeMap<u32 col, Cell>>` |
//! | `<c r="A1">` | [`Cell`](参见 [`crate::cell`]) |
//!
//! # 设计取舍
//!
//! - **`rows` 用 `BTreeMap<u32, BTreeMap<u32, Cell>>` 双层映射**:
//!   外层按行号排序,内层按列号排序。这样 `iter_cells()` 输出顺序与 Excel 输出一致
//!   (从上到下、从左到右),便于 byte-diff 测试。
//! - **`String` 与 `SharedString` 的转换由 `to_xml` / `from_xml` 在边界完成**:
//!   `Worksheet::set_cell` 接受用户友好的 `CellValue::String`,内部直接存原值;
//!   `to_xml(sst: &mut SharedStringsTable)` 在写出 `<c>` 时把 `String` 注册到 SST 得到 idx,
//!   写出 `<c t="s"><v>idx</v></c>`;`from_xml(xml, sst)` 在解析时遇到 `t="s"` 反查 SST
//!   还原为 `String`。这样 round-trip 时 SST 索引可能变化但 cell 内容一致。
//! - **不持有 SST 引用**:`Worksheet` 与 `SharedStringsTable` 解耦,
//!   SST 由 `Workbook` 统一管理(多 sheet 共享),`to_xml` / `from_xml` 通过参数注入。

use std::collections::BTreeMap;

use crate::cell::{parse_a1, to_a1, Cell, CellType, CellValue};
use crate::error::{Error, Result};
use crate::shared_strings::SharedStringsTable;

/// SpreadsheetML 命名空间。
const NS_SPREADSHEETML: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

/// 一个工作表(对应 `xl/worksheets/sheetN.xml`)。
#[derive(Debug, Clone)]
pub struct Worksheet {
    /// 工作表名称(显示在 Excel 底部 Tab)。
    name: String,
    /// 单元格数据:`row (1-indexed) → (col (1-indexed) → Cell)`。
    /// 用 `BTreeMap` 保证 iter 顺序稳定(行号、列号升序)。
    rows: BTreeMap<u32, BTreeMap<u32, Cell>>,
}

impl Worksheet {
    /// 构造一个空工作表。
    pub fn new(name: impl Into<String>) -> Self {
        Worksheet {
            name: name.into(),
            rows: BTreeMap::new(),
        }
    }

    /// 工作表名称。
    pub fn name(&self) -> &str {
        &self.name
    }

    /// 重命名工作表。
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = name.into();
    }

    /// 设置单元格(用户友好 API)。
    ///
    /// - 自动解析 `reference`(如 `"A1"` / `"B12"`)得到 `(row, col)`;
    /// - 如果 `value` 是 `CellValue::String`,**不**在此处注册 SharedStrings,
    ///   留待 `to_xml` 时统一处理(保证多 sheet 共享同一 SST);
    /// - 如果 `value` 是 `CellValue::Empty`,移除该 cell(与 Excel 行为一致)。
    ///
    /// # 错误
    /// - [`Error::InvalidCellRef`]:`reference` 不是合法 A1 形式。
    pub fn set_cell(&mut self, reference: &str, value: CellValue) -> Result<()> {
        let (row, col) = parse_a1(reference)?;
        self.set_cell_rc(row, col, value);
        Ok(())
    }

    /// 设置单元格(按行列号,1-indexed)。
    ///
    /// 与 [`Worksheet::set_cell`] 等价,但跳过 A1 解析,适用于批量写入。
    pub fn set_cell_rc(&mut self, row: u32, col: u32, value: CellValue) {
        if value.is_empty() {
            // Empty 视为清除 cell
            if let Some(row_map) = self.rows.get_mut(&row) {
                row_map.remove(&col);
                if row_map.is_empty() {
                    self.rows.remove(&row);
                }
            }
            return;
        }
        let reference = to_a1(row, col);
        let cell = Cell::new(reference, value);
        self.rows.entry(row).or_default().insert(col, cell);
    }

    /// 取单元格(按 A1 引用)。
    pub fn get_cell(&self, reference: &str) -> Result<Option<&Cell>> {
        let (row, col) = parse_a1(reference)?;
        Ok(self.get_cell_rc(row, col))
    }

    /// 取单元格(按行列号)。
    pub fn get_cell_rc(&self, row: u32, col: u32) -> Option<&Cell> {
        self.rows.get(&row).and_then(|r| r.get(&col))
    }

    /// 取单元格的可变引用(按 A1 引用)。
    pub fn get_cell_mut(&mut self, reference: &str) -> Result<Option<&mut Cell>> {
        let (row, col) = parse_a1(reference)?;
        Ok(self.rows.get_mut(&row).and_then(|r| r.get_mut(&col)))
    }

    /// 迭代所有 cell(按行号、列号升序)。
    pub fn iter_cells(&self) -> impl Iterator<Item = &Cell> {
        self.rows.values().flat_map(|r| r.values())
    }

    /// 迭代所有行(按行号升序)。
    pub fn iter_rows(&self) -> impl Iterator<Item = (u32, &BTreeMap<u32, Cell>)> {
        self.rows.iter().map(|(r, m)| (*r, m))
    }

    /// 非空 cell 数量。
    pub fn cell_count(&self) -> usize {
        self.rows.values().map(|r| r.len()).sum()
    }

    /// 是否为空表(无 cell)。
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// 最大行号(存在 cell 的最大行)。
    pub fn max_row(&self) -> Option<u32> {
        self.rows.keys().copied().max()
    }

    /// 最大列号(所有行中存在 cell 的最大列)。
    pub fn max_col(&self) -> Option<u32> {
        self.rows.values().flat_map(|r| r.keys().copied()).max()
    }

    /// 计算 `<dimension ref="A1:MaxColMaxRow"/>` 字符串。
    ///
    /// 空表返回 `"A1"`(OOXML 允许 dimension 仅含左上角)。
    pub fn dimension(&self) -> String {
        match (self.max_row(), self.max_col()) {
            (None, _) | (_, None) => "A1".to_string(),
            (Some(1), Some(1)) => "A1".to_string(),
            (Some(max_r), Some(max_c)) => format!("A1:{}", to_a1(max_r, max_c)),
        }
    }

    /// 清空所有 cell。
    pub fn clear(&mut self) {
        self.rows.clear();
    }

    /// 序列化为 `<worksheet>` 元素的 XML 字符串。
    ///
    /// # 参数
    /// - `sst`:可变引用的 SharedStringsTable。`String` 值会在此注册得到索引,
    ///   写出 `<c t="s"><v>idx</v></c>`。多 sheet 共享同一 SST 实例。
    ///
    /// # 输出格式
    ///
    /// ```xml
    /// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    /// <worksheet xmlns="...">
    ///   <dimension ref="A1:C3"/>
    ///   <sheetData>
    ///     <row r="1"><c r="A1"><v>1</v></c>...</row>
    ///     <row r="2"><c r="A2" t="s"><v>0</v></c>...</row>
    ///   </sheetData>
    /// </worksheet>
    /// ```
    pub fn to_xml(&self, sst: &mut SharedStringsTable) -> String {
        let mut s = String::with_capacity(256);
        s.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n");
        s.push_str(&format!("<worksheet xmlns=\"{}\">", NS_SPREADSHEETML));

        // dimension
        s.push_str(&format!("<dimension ref=\"{}\"/>", self.dimension()));

        // sheetData
        s.push_str("<sheetData>");
        for (row_idx, row_map) in &self.rows {
            s.push_str(&format!("<row r=\"{}\">", row_idx));
            for (_col_idx, cell) in row_map {
                // 把 String 转换为 SharedString(idx) 后写出
                let cell_to_write = match &cell.value {
                    CellValue::String(text) => {
                        let idx = sst.add(text);
                        let mut c2 = cell.clone();
                        c2.value = CellValue::SharedString(idx);
                        c2
                    }
                    _ => cell.clone(),
                };
                s.push_str(&cell_to_write.to_xml());
            }
            s.push_str("</row>");
        }
        s.push_str("</sheetData>");
        s.push_str("</worksheet>");
        s
    }

    /// 从 `<worksheet>` 元素的 XML 字符串解析。
    ///
    /// # 参数
    /// - `xml`:worksheet XML 文本;
    /// - `sst`:SharedStringsTable 引用。`t="s"` 的 cell 会通过索引反查还原为 `String`。
    ///
    /// # 错误
    /// - [`Error::Xml`]:XML 解析失败;
    /// - [`Error::Schema`]:cell 类型未知 / SharedString 索引越界;
    /// - [`Error::InvalidCellRef`]:cell `r` 属性非法。
    pub fn from_xml(xml: &str, sst: &SharedStringsTable) -> Result<Self> {
        use quick_xml::events::Event;
        use quick_xml::reader::Reader;

        let mut ws = Worksheet::new("");
        let mut rd = Reader::from_str(xml);
        // 不开启 trim_text:见 shared_strings.rs 同样注释。数字解析时手动 trim()。
        let mut buf = Vec::new();

        // 状态机:sheetData → row → c → v/is/t
        let mut in_sheetdata = false;
        let mut in_row = false;
        let mut in_c = false;
        let mut in_v = false;
        let mut in_is = false;
        let mut in_t = false;

        let mut cur_ref: Option<String> = None;
        let mut cur_type: Option<CellType> = None;
        let mut cur_text = String::new();

        loop {
            match rd.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => match e.name().as_ref() {
                    b"sheetData" => in_sheetdata = true,
                    b"row" if in_sheetdata => {
                        in_row = true;
                    }
                    b"c" if in_row => {
                        in_c = true;
                        cur_ref = None;
                        cur_type = None;
                        cur_text.clear();
                        for attr in e.attributes().flatten() {
                            match attr.key.as_ref() {
                                b"r" => {
                                    cur_ref = Some(
                                        attr.normalized_value(quick_xml::XmlVersion::Implicit1_0)
                                            .ok()
                                            .map(|v| v.to_string())
                                            .unwrap_or_default(),
                                    );
                                }
                                b"t" => {
                                    let v = attr
                                        .normalized_value(quick_xml::XmlVersion::Implicit1_0)
                                        .ok()
                                        .map(|v| v.to_string());
                                    cur_type = Some(CellType::from_str(v.as_deref())?);
                                }
                                _ => {}
                            }
                        }
                    }
                    b"v" if in_c => in_v = true,
                    b"is" if in_c => in_is = true,
                    b"t" if in_is => in_t = true,
                    _ => {}
                },
                Ok(Event::Empty(e)) if in_row && e.name().as_ref() == b"c" => {
                    // <c r="A1"/> 空 cell:跳过(不存入 rows)
                    continue;
                }
                Ok(Event::End(e)) => match e.name().as_ref() {
                    b"v" => in_v = false,
                    b"is" => in_is = false,
                    b"t" => in_t = false,
                    b"c" => {
                        // cell 收尾:构造 CellValue 并存入 rows
                        if let Some(reference) = cur_ref.take() {
                            let value = build_cell_value(
                                cur_type.unwrap_or(CellType::Number),
                                &cur_text,
                                sst,
                            )?;
                            if !value.is_empty() {
                                let (row, col) = parse_a1(&reference)?;
                                ws.rows
                                    .entry(row)
                                    .or_default()
                                    .insert(col, Cell::new(reference, value));
                            }
                        }
                        in_c = false;
                        cur_text.clear();
                        cur_type = None;
                    }
                    b"row" => in_row = false,
                    b"sheetData" => in_sheetdata = false,
                    _ => {}
                },
                Ok(Event::Text(t)) if in_v || in_t => {
                    // quick-xml 0.40 的 Text 事件只夹带纯文本字节,entity(`&lt;` 等)
                    // 被拆成独立的 GeneralRef 事件,因此这里直接 UTF-8 解码即可,无需 unescape。
                    let text_str = std::str::from_utf8(t.as_ref()).unwrap_or("");
                    cur_text.push_str(text_str);
                }
                Ok(Event::GeneralRef(r)) if in_v || in_t => {
                    // quick-xml 0.40 把 `&lt;` `&gt;` `&amp;` `&#60;` 等 entity reference
                    // 作为独立的 GeneralRef 事件发出。这里手动解析 entity 并追加到 cur_text,
                    // 否则特殊字符(`<` `>` `&` `"` `'`)会在 round-trip 中丢失。
                    // 先尝试字符引用(`&#60;` / `&#x3C;`),再回退到 5 个预定义命名 entity。
                    if let Some(ch) = r
                        .resolve_char_ref()
                        .map_err(|e| Error::Xml(format!("worksheet char ref: {e}")))?
                    {
                        cur_text.push(ch);
                    } else {
                        let name = r
                            .decode()
                            .map_err(|e| Error::Xml(format!("worksheet entity decode: {e}")))?;
                        let ch = match name.as_ref() {
                            "lt" => '<',
                            "gt" => '>',
                            "amp" => '&',
                            "quot" => '"',
                            "apos" => '\'',
                            other => {
                                return Err(Error::Xml(format!(
                                    "worksheet unknown entity: &{other};"
                                )))
                            }
                        };
                        cur_text.push(ch);
                    }
                }
                Ok(Event::CData(t)) if in_v || in_t => {
                    if let Ok(s) = std::str::from_utf8(&t) {
                        cur_text.push_str(s);
                    }
                }
                Ok(Event::Eof) => break,
                Ok(_) => {}
                Err(e) => return Err(Error::Xml(format!("worksheet parse: {e}"))),
            }
            buf.clear();
        }
        Ok(ws)
    }
}

/// 根据 cell_type 和文本构造 CellValue(SharedString 反查 SST 还原为 String)。
fn build_cell_value(
    cell_type: CellType,
    text: &str,
    sst: &SharedStringsTable,
) -> Result<CellValue> {
    match cell_type {
        CellType::Number => {
            if text.is_empty() {
                Ok(CellValue::Empty)
            } else {
                let n = text
                    .trim()
                    .parse::<f64>()
                    .map_err(|e| Error::Schema(format!("cell number parse: {e}")))?;
                Ok(CellValue::Number(n))
            }
        }
        CellType::Boolean => {
            let b = match text.trim() {
                "1" | "true" => true,
                "0" | "false" => false,
                other => return Err(Error::Schema(format!("cell boolean parse: '{}'", other))),
            };
            Ok(CellValue::Boolean(b))
        }
        CellType::Error => Ok(CellValue::Error(text.to_string())),
        CellType::SharedString => {
            let i = text
                .trim()
                .parse::<usize>()
                .map_err(|e| Error::Schema(format!("cell shared index parse: {e}")))?;
            sst.get(i)
                .map(|s| CellValue::String(s.to_string()))
                .ok_or_else(|| Error::Schema(format!("shared string index out of range: {}", i)))
        }
        CellType::FormulaString => Ok(CellValue::String(text.to_string())),
        CellType::InlineString => Ok(CellValue::String(text.to_string())),
    }
}

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

    fn make_sheet() -> Worksheet {
        let mut ws = Worksheet::new("Sheet1");
        ws.set_cell("A1", CellValue::Number(1.0)).unwrap();
        ws.set_cell("B1", CellValue::Number(2.0)).unwrap();
        ws.set_cell("A2", CellValue::String("Hello".to_string()))
            .unwrap();
        ws.set_cell("B2", CellValue::Boolean(true)).unwrap();
        ws
    }

    #[test]
    fn set_and_get_cell() {
        let ws = make_sheet();
        assert_eq!(
            ws.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::Number(1.0)
        );
        assert_eq!(
            ws.get_cell("A2").unwrap().unwrap().value(),
            &CellValue::String("Hello".to_string())
        );
        assert_eq!(
            ws.get_cell("B2").unwrap().unwrap().value(),
            &CellValue::Boolean(true)
        );
        assert!(ws.get_cell("C5").unwrap().is_none());
    }

    #[test]
    fn set_cell_rc_skips_a1_parse() {
        let mut ws = Worksheet::new("Sheet1");
        ws.set_cell_rc(3, 5, CellValue::Number(42.0));
        assert_eq!(
            ws.get_cell_rc(3, 5).unwrap().value(),
            &CellValue::Number(42.0)
        );
        assert_eq!(ws.get_cell_rc(3, 5).unwrap().reference(), "E3");
    }

    #[test]
    fn empty_value_removes_cell() {
        let mut ws = Worksheet::new("Sheet1");
        ws.set_cell("A1", CellValue::Number(1.0)).unwrap();
        assert!(ws.get_cell("A1").unwrap().is_some());
        ws.set_cell("A1", CellValue::Empty).unwrap();
        assert!(ws.get_cell("A1").unwrap().is_none());
        assert!(ws.is_empty());
    }

    #[test]
    fn invalid_reference_errors() {
        let mut ws = Worksheet::new("Sheet1");
        assert!(ws.set_cell("XYZ", CellValue::Number(1.0)).is_err());
        assert!(ws.get_cell("XYZ").is_err());
    }

    #[test]
    fn dimension_calculation() {
        let ws = make_sheet();
        assert_eq!(ws.dimension(), "A1:B2");
    }

    #[test]
    fn dimension_empty() {
        let ws = Worksheet::new("Sheet1");
        assert_eq!(ws.dimension(), "A1");
    }

    #[test]
    fn dimension_single_cell() {
        let mut ws = Worksheet::new("Sheet1");
        ws.set_cell("A1", CellValue::Number(1.0)).unwrap();
        assert_eq!(ws.dimension(), "A1");
    }

    #[test]
    fn iter_cells_order() {
        let ws = make_sheet();
        let cells: Vec<&Cell> = ws.iter_cells().collect();
        // 顺序:A1, B1, A2, B2(行号优先,列号次之)
        assert_eq!(cells.len(), 4);
        assert_eq!(cells[0].reference(), "A1");
        assert_eq!(cells[1].reference(), "B1");
        assert_eq!(cells[2].reference(), "A2");
        assert_eq!(cells[3].reference(), "B2");
    }

    #[test]
    fn cell_count() {
        let ws = make_sheet();
        assert_eq!(ws.cell_count(), 4);
    }

    #[test]
    fn max_row_col() {
        let ws = make_sheet();
        assert_eq!(ws.max_row(), Some(2));
        assert_eq!(ws.max_col(), Some(2));
    }

    #[test]
    fn to_xml_basic_structure() {
        let ws = make_sheet();
        let mut sst = SharedStringsTable::new();
        let xml = ws.to_xml(&mut sst);

        assert!(xml.contains("<?xml version=\"1.0\""));
        assert!(xml.contains("<worksheet xmlns=\""));
        assert!(xml.contains("<dimension ref=\"A1:B2\"/>"));
        assert!(xml.contains("<sheetData>"));
        assert!(xml.contains("<row r=\"1\">"));
        assert!(xml.contains("<row r=\"2\">"));
        // A1 是数字,无 t 属性
        assert!(xml.contains("<c r=\"A1\"><v>1</v></c>"));
        // A2 是字符串,会被注册到 sst 并写出 t="s"
        assert!(xml.contains("<c r=\"A2\" t=\"s\"><v>0</v></c>"));
        // B2 是布尔
        assert!(xml.contains("<c r=\"B2\" t=\"b\"><v>1</v></c>"));
    }

    #[test]
    fn to_xml_registers_strings_in_sst() {
        let ws = make_sheet();
        let mut sst = SharedStringsTable::new();
        let _xml = ws.to_xml(&mut sst);
        assert_eq!(sst.unique_count(), 1); // "Hello"
        assert_eq!(sst.get(0), Some("Hello"));
    }

    #[test]
    fn from_xml_round_trip() {
        let ws = make_sheet();
        let mut sst = SharedStringsTable::new();
        let xml = ws.to_xml(&mut sst);
        let ws2 = Worksheet::from_xml(&xml, &sst).unwrap();

        assert_eq!(ws2.cell_count(), 4);
        assert_eq!(
            ws2.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::Number(1.0)
        );
        assert_eq!(
            ws2.get_cell("A2").unwrap().unwrap().value(),
            &CellValue::String("Hello".to_string())
        );
        assert_eq!(
            ws2.get_cell("B2").unwrap().unwrap().value(),
            &CellValue::Boolean(true)
        );
    }

    #[test]
    fn from_xml_empty_sheet() {
        let xml = "<?xml version=\"1.0\"?>\
                   <worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">\
                   <dimension ref=\"A1\"/>\
                   <sheetData/>\
                   </worksheet>";
        let sst = SharedStringsTable::new();
        let ws = Worksheet::from_xml(xml, &sst).unwrap();
        assert!(ws.is_empty());
    }

    #[test]
    fn from_xml_shared_string_resolves() {
        let xml = "<?xml version=\"1.0\"?>\
                   <worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">\
                   <sheetData>\
                     <row r=\"1\"><c r=\"A1\" t=\"s\"><v>0</v></c></row>\
                   </sheetData>\
                   </worksheet>";
        let mut sst = SharedStringsTable::new();
        sst.add("World");
        let ws = Worksheet::from_xml(xml, &sst).unwrap();
        assert_eq!(
            ws.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::String("World".to_string())
        );
    }

    #[test]
    fn from_xml_shared_string_out_of_range_errors() {
        let xml = "<?xml version=\"1.0\"?>\
                   <worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">\
                   <sheetData>\
                     <row r=\"1\"><c r=\"A1\" t=\"s\"><v>99</v></c></row>\
                   </sheetData>\
                   </worksheet>";
        let sst = SharedStringsTable::new();
        assert!(Worksheet::from_xml(xml, &sst).is_err());
    }

    #[test]
    fn round_trip_preserves_special_chars() {
        let mut ws = Worksheet::new("Sheet1");
        ws.set_cell("A1", CellValue::String("a<b>&c".to_string()))
            .unwrap();
        let mut sst = SharedStringsTable::new();
        let xml = ws.to_xml(&mut sst);
        let ws2 = Worksheet::from_xml(&xml, &sst).unwrap();
        assert_eq!(
            ws2.get_cell("A1").unwrap().unwrap().value(),
            &CellValue::String("a<b>&c".to_string())
        );
    }

    #[test]
    fn rename_sheet() {
        let mut ws = Worksheet::new("Old");
        ws.set_name("New");
        assert_eq!(ws.name(), "New");
    }

    #[test]
    fn clear_empties_sheet() {
        let mut ws = make_sheet();
        assert_eq!(ws.cell_count(), 4);
        ws.clear();
        assert!(ws.is_empty());
    }
}