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
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io;
use std::path::Path;
use std::string::FromUtf8Error;
use std::sync::Arc;
use std::sync::RwLock;

use super::driver;
use structs::drawing::Theme;
use structs::raw::RawWorksheet;
use structs::SharedStringTable;
use structs::Spreadsheet;
use structs::Stylesheet;
use structs::Worksheet;

pub(crate) mod chart;
pub(crate) mod comment;
mod content_types;
mod doc_props_app;
mod doc_props_core;
pub(crate) mod drawing;
mod rels;
mod shared_strings;
mod styles;
mod theme;
mod vba_project_bin;
pub(crate) mod vml_drawing;
mod workbook;
mod workbook_rels;
pub(crate) mod worksheet;

#[derive(Debug)]
pub enum XlsxError {
    Io(io::Error),
    Xml(quick_xml::Error),
    Zip(zip::result::ZipError),
    Uft8(FromUtf8Error),
}

impl From<io::Error> for XlsxError {
    fn from(err: io::Error) -> XlsxError {
        XlsxError::Io(err)
    }
}

impl From<quick_xml::Error> for XlsxError {
    fn from(err: quick_xml::Error) -> XlsxError {
        XlsxError::Xml(err)
    }
}

impl From<zip::result::ZipError> for XlsxError {
    fn from(err: zip::result::ZipError) -> XlsxError {
        XlsxError::Zip(err)
    }
}

impl From<FromUtf8Error> for XlsxError {
    fn from(err: FromUtf8Error) -> XlsxError {
        XlsxError::Uft8(err)
    }
}
impl fmt::Display for XlsxError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::XlsxError::*;
        match self {
            Io(i) => write!(f, "IoError: {}", i),
            Xml(s) => write!(f, "XmlError: {}", s),
            Zip(s) => write!(f, "ZipError: {}", s),
            Uft8(s) => write!(f, "Uft8Error: {}", s),
        }
    }
}

impl Error for XlsxError {}

/// read spreadsheet from arbitrary reader.
/// # Arguments
/// * `reader` - reader to read from.
/// # Return value
/// * `Result` - OK is Spreadsheet. Err is error message.
pub fn read_reader<R: io::Read + io::Seek>(
    reader: R,
    with_sheet_read: bool,
) -> Result<Spreadsheet, XlsxError> {
    let mut arv = zip::read::ZipArchive::new(reader)?;

    let mut book = workbook::read(&mut arv).unwrap();
    doc_props_app::read(&mut arv, &mut book).unwrap();
    doc_props_core::read(&mut arv, &mut book).unwrap();
    vba_project_bin::read(&mut arv, &mut book).unwrap();
    content_types::read(&mut arv, &mut book).unwrap();
    let workbook_rel = workbook_rels::read(&mut arv, &mut book).unwrap();

    book.set_theme(Theme::get_defalut_value());
    for (_, type_value, rel_target) in &workbook_rel {
        match type_value.as_str() {
            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" => {
                let theme = theme::read(&mut arv, rel_target).unwrap();
                book.set_theme(theme);
            }
            _ => {}
        }
    }

    shared_strings::read(&mut arv, &mut book).unwrap();
    styles::read(&mut arv, &mut book).unwrap();

    for sheet in book.get_sheet_collection_mut() {
        for (rel_id, _, rel_target) in &workbook_rel {
            if sheet.get_r_id() != rel_id {
                continue;
            }
            let mut raw_worksheet = RawWorksheet::default();
            raw_worksheet.read(&mut arv, rel_target);
            sheet.set_raw_data_of_worksheet(raw_worksheet);
        }
    }

    if with_sheet_read {
        book.read_sheet_collection();
    }

    Ok(book)
}

/// read spreadsheet file.
/// # Arguments
/// * `path` - file path to read.
/// # Return value
/// * `Result` - OK is Spreadsheet. Err is error message.
/// # Examples
/// ```
/// let path = std::path::Path::new("./tests/test_files/aaa.xlsx");
/// let mut book = umya_spreadsheet::reader::xlsx::read(path).unwrap();
/// ```
pub fn read<P: AsRef<Path>>(path: P) -> Result<Spreadsheet, XlsxError> {
    let file = File::open(path)?;
    read_reader(file, true)
}

/// lazy read spreadsheet file.
/// Delays the loading of the worksheet until it is needed.
/// When loading a file with a large amount of data, response improvement can be expected.
/// # Arguments
/// * `path` - file path to read.
/// # Return value
/// * `Result` - OK is Spreadsheet. Err is error message.
/// # Examples
/// ```
/// let path = std::path::Path::new("./tests/test_files/aaa.xlsx");
/// let mut book = umya_spreadsheet::reader::xlsx::lazy_read(path).unwrap();
/// ```
pub fn lazy_read(path: &Path) -> Result<Spreadsheet, XlsxError> {
    let file = File::open(path)?;
    read_reader(file, false)
}

pub(crate) fn raw_to_deserialize_by_worksheet(
    worksheet: &mut Worksheet,
    theme: &Theme,
    shared_string_table: Arc<RwLock<SharedStringTable>>,
    stylesheet: &Stylesheet,
) {
    if worksheet.is_deserialized() {
        return;
    }

    let raw_data_of_worksheet = worksheet.get_raw_data_of_worksheet().clone();
    let shared_string_table = &*shared_string_table.read().unwrap();
    worksheet::read(
        worksheet,
        &raw_data_of_worksheet,
        theme,
        shared_string_table,
        stylesheet,
    )
    .unwrap();

    match raw_data_of_worksheet.get_worksheet_relationships() {
        Some(v) => {
            for relationship in v.get_relationship_list() {
                match relationship.get_type() {
                    // drawing, chart
                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" => {
                        drawing::read(
                            worksheet,
                            relationship.get_raw_file(),
                            raw_data_of_worksheet.get_drawing_relationships(),
                        )
                        .unwrap();
                    }
                    // comment
                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" => {
                        comment::read(worksheet, relationship.get_raw_file()).unwrap();
                    }
                    _ => {}
                }
            }
            for relationship in v.get_relationship_list() {
                match relationship.get_type() {
                    // vmlDrawing
                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" => {
                        vml_drawing::read(
                            worksheet,
                            relationship.get_raw_file(),
                            raw_data_of_worksheet.get_vml_drawing_relationships(),
                        )
                        .unwrap();
                    }
                    _ => {}
                }
            }
        }
        None => {}
    }

    worksheet.remove_raw_data_of_worksheet();
}