Skip to main content

ironcalc_base/
workbook.rs

1use std::vec::Vec;
2
3use crate::{expressions::parser::DefinedNameS, types::*};
4
5impl Workbook {
6    pub fn get_worksheet_names(&self) -> Vec<String> {
7        self.worksheets
8            .iter()
9            .map(|worksheet| worksheet.get_name())
10            .collect()
11    }
12    pub fn get_worksheet_ids(&self) -> Vec<u32> {
13        self.worksheets
14            .iter()
15            .map(|worksheet| worksheet.get_sheet_id())
16            .collect()
17    }
18
19    pub fn worksheet(&self, worksheet_index: u32) -> Result<&Worksheet, String> {
20        self.worksheets
21            .get(worksheet_index as usize)
22            .ok_or_else(|| "Invalid sheet index".to_string())
23    }
24
25    pub fn worksheet_mut(&mut self, worksheet_index: u32) -> Result<&mut Worksheet, String> {
26        self.worksheets
27            .get_mut(worksheet_index as usize)
28            .ok_or_else(|| "Invalid sheet index".to_string())
29    }
30
31    /// Returns the a list of defined names in the workbook with their scope
32    pub fn get_defined_names_with_scope(&self) -> Vec<DefinedNameS> {
33        let sheet_id_index: Vec<u32> = self.worksheets.iter().map(|s| s.sheet_id).collect();
34
35        let defined_names = self
36            .defined_names
37            .iter()
38            .map(|dn| {
39                let index = dn
40                    .sheet_id
41                    .and_then(|sheet_id| {
42                        // returns an Option<usize>
43                        sheet_id_index.iter().position(|&x| x == sheet_id)
44                    })
45                    // convert Option<usize> to Option<u32>
46                    .map(|pos| pos as u32);
47
48                (dn.name.clone(), index, dn.formula.clone())
49            })
50            .collect::<Vec<_>>();
51        defined_names
52    }
53}