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
use polars::prelude::{strings, AnyValue, TimeUnit};
use quick_xml::Reader;
use quick_xml::{events::Event,name::QName};
use std::cell;
use std::collections::HashMap;
use std::fs::{self,File};
use std::io::{BufReader, Read};
use std::sync::Arc;
use zip::ZipArchive;
use rayon::prelude::*;
use crate::ws::{SheetReader, Worksheet};
use crate::utils;
use crate::cellvalue::{Cell, Range,CellFormat,get_cell_format};
#[derive(Debug,Clone)]
pub enum DateSystem {
V1900,
V1904,
}
#[derive(Debug)]
pub struct Workbook {
pub path: String,
xls: ZipArchive<fs::File>,
encoding: String,
pub date_system: DateSystem,
pub strings: Vec<String>,
pub styles: Vec<CellFormat>,
threads: usize,
}
#[derive(Debug)]
pub struct SheetMap {
sheets_by_name: HashMap::<String, u8>,
sheets_by_num: Vec<Option<Worksheet>>,
}
impl SheetMap {
pub fn sheet_names(&self) -> Vec<&str> {
self.sheets_by_name.keys().map(|k| k as &str).collect()
}
}
pub enum SheetNameOrNum<'a> {
Name(&'a str),
Pos(usize),
}
pub trait SheetAccessTrait { fn go(&self) -> SheetNameOrNum; }
impl SheetAccessTrait for &str {
fn go(&self) -> SheetNameOrNum { SheetNameOrNum::Name(*self) }
}
impl SheetAccessTrait for usize {
fn go(&self) -> SheetNameOrNum { SheetNameOrNum::Pos(*self) }
}
impl SheetMap {
/// An easy way to obtain a reference to a `Worksheet` within this `Workbook`. Note that we
/// return an `Option` because the sheet you want may not exist in the workbook. Also note that
/// when you try to `get` a worksheet by number (i.e., by its position within the workbook),
/// the tabs use **1-based indexing** rather than 0-based indexing (like the rest of Rust and
/// most of the programming world). This was an intentional design choice to make things
/// consistent with VBA. It's possible it may change in the future, but it seems intuitive
/// enough if you are familiar with VBA and Excel programming, so it may not.
///
/// # Example usage
///
/// use xl::{Workbook, Worksheet};
///
/// let mut wb = Workbook::open("tests/data/Book1.xlsx").unwrap();
/// let sheets = wb.sheets();
///
/// // by sheet name
/// let time_sheet = sheets.get("Time");
/// assert!(time_sheet.is_some());
///
/// // unknown sheet name
/// let unknown_sheet = sheets.get("not in this workbook");
/// assert!(unknown_sheet.is_none());
///
/// // by position
/// let unknown_sheet = sheets.get(1);
/// assert_eq!(unknown_sheet.unwrap().name, "Sheet1");
pub fn get<T: SheetAccessTrait>(&self, sheet: T) -> Option<&Worksheet> {
let sheet = sheet.go();
match sheet {
SheetNameOrNum::Name(n) => {
match self.sheets_by_name.get(n) {
Some(p) => self.sheets_by_num.get(*p as usize)?.as_ref(),
None => None
}
},
SheetNameOrNum::Pos(n) => self.sheets_by_num.get(n)?.as_ref(),
}
}
/// The number of active sheets in the workbook.
///
/// # Example usage
///
/// use xl::{Workbook, Worksheet};
///
/// let mut wb = Workbook::open("tests/data/Book1.xlsx").unwrap();
/// let sheets = wb.sheets();
/// assert_eq!(sheets.len(), 4);
pub fn len(&self) -> u8 {
(self.sheets_by_num.len() - 1) as u8
}
}
impl Workbook {
/// xlsx zips contain an xml file that has a mapping of "ids" to "targets." The ids are used
/// to uniquely identify sheets within the file. The targets have information on where the
/// sheets can be found within the zip. This function returns a hashmap of id -> target so that
/// you can quickly determine the name of the sheet xml file within the zip.
fn rels(&mut self) -> HashMap<String, String> {
let mut map = HashMap::new();
match self.xls.by_name("xl/_rels/workbook.xml.rels") {
Ok(rels) => {
// Looking for tree structure like:
// Relationships
// Relationship(id = "abc", target = "def")
// Relationship(id = "ghi", target = "lkm")
// etc.
// Each relationship contains an id that is used to reference
// the sheet and a target which tells us where we can find the
// sheet in the zip file.
//
// Uncomment the following line to print out a copy of what
// the xml looks like (will probably not be too big).
// let _ = std::io::copy(&mut rels, &mut std::io::stdout());
let reader = BufReader::new(rels);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Empty(ref e)) if e.name() == QName(b"Relationship") => {
let mut id = String::new();
let mut target = String::new();
e.attributes()
.for_each(|a| {
let a = a.unwrap();
if a.key == QName(b"Id") {
id = utils::attr_value(&a);
}
if a.key == QName(b"Target") {
target = utils::attr_value(&a);
}
});
map.insert(id, target);
},
Ok(Event::Eof) => break, // exits the loop when reaching end of file
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (), // There are several other `Event`s we do not consider here
}
buf.clear();
}
map
},
Err(_) => map
}
}
/// Set the number of threads to use when reading the workbook. The default is 1.
/// In oder to accelerate reading, you can set the number of threads to use.
pub fn set_threads_num(&mut self, num: usize){
if num >1{
self.threads = num;
}
}
/// Return `SheetMap` of all sheets in this workbook. See `SheetMap` class and associated
/// methods for more detailed documentation.
pub fn sheets(&mut self) -> SheetMap {
let rels = self.rels();
let num_sheets = rels.iter().filter(|(_, v)| v.starts_with("worksheet")).count();
let mut sheets = SheetMap {
sheets_by_name: HashMap::new(),
sheets_by_num: Vec::with_capacity(num_sheets + 1),
};
sheets.sheets_by_num.push(None); // never a "0" sheet (consistent with VBA)
match self.xls.by_name("xl/workbook.xml") {
Ok(wb) => {
// let _ = std::io::copy(&mut wb, &mut std::io::stdout());
let reader = BufReader::new(wb);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut current_sheet_num: u8 = 0;
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Empty(ref e)) if e.name() == QName(b"sheet") => {
current_sheet_num += 1;
let mut name = String::new();
let mut id = String::new();
let mut num = 0;
e.attributes()
.for_each(|a| {
let a = a.unwrap();
if a.key == QName(b"r:id") {
id = utils::attr_value(&a);
}
if a.key == QName(b"name") {
name = utils::attr_value(&a);
}
if a.key == QName(b"sheetId") {
if let Ok(r) = utils::attr_value(&a).parse() {
num = r;
}
}
});
sheets.sheets_by_name.insert(name.clone(), current_sheet_num);
let target = {
let s = rels.get(&id).unwrap();
if let Some(stripped) = s.strip_prefix('/') {
stripped.to_string()
} else {
"xl/".to_owned() + s
}
};
let ws = Worksheet::new(id, name, current_sheet_num, target, num);
sheets.sheets_by_num.push(Some(ws));
},
Ok(Event::Eof) => {
break
},
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
sheets
},
Err(_) => sheets
}
}
pub fn get_sheet_range2<'a>(&mut self, sheet: &str) ->Range<'a>{
if self.threads <2{
self.threads =2;
}
self.strings = strings2(&mut self.xls, self.threads);
let sheet_map = self.sheets();
let target_sheet = match sheet_map.get(sheet) {
Some(r) => r,
None => panic!("无法获取sheet"),
};
let (data,mut reader) = self.sheet_reader2(&target_sheet.target);
let share_strings = Arc::new(self.strings.to_owned());
let styles = Arc::new(self.styles.to_owned());
let date_system = Arc::new(self.date_system.clone());
let chunker = utils::XmlChunker::new(&data, self.threads,utils::ROW_END);
let chunks = chunker.chunks(); // Convert chunks to Arc<[u8]>
let res: Vec<Cell> = chunks
.into_par_iter()
.flat_map(|chunk| {
// Pass Arc-wrapped shared data
utils::get_cell_data_from_chunk(
&chunk.to_owned(), // Pass owned chunk
Arc::clone(&share_strings), // Clone Arc reference
Arc::clone(&styles), // Clone Arc reference
Arc::clone(&date_system), // Clone Arc reference
)
})
.flatten()
.collect();
let mut max_col = 1;
for c in res.iter().map(|c| c.pos.1){
if c > max_col {
max_col = c;
}
}
let max_row = res.last().unwrap().pos.0;
let len = max_col * max_row;
let mut range: Range<'_> = Range { cells: vec![Cell::new(); len], max_col:max_col};
for cell in res {
let idx = (cell.pos.0-1) * max_col as usize + cell.pos.1 -1;
range.cells[idx] = cell;
}
range
}
pub fn get_sheet_range(&mut self, sheet: &str) ->Range<'_>{
self.strings = strings(&mut self.xls);
let sheet_map = self.sheets();
let target_sheet = match sheet_map.get(sheet) {
Some(r) => r,
None => panic!("无法获取sheet"),
};
let mut sheet_reader = self.sheet_reader(&target_sheet.target);
let mut buf = Vec::new();
let mut in_value = false;
let mut is_string = false;
let mut is_inlinstring = false;
let mut in_cell = false;
let mut max_col = 1;
let mut cells = Vec::with_capacity(2000);
let mut cell_row =0;
let mut cell_col =0;
let mut each_col_count =0;
let mut cell_format = CellFormat::Number;
loop {
match sheet_reader.reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.name().as_ref() == b"row" =>{
each_col_count =0;
},
Ok(Event::End(ref e)) if e.name().as_ref() == b"row" =>{
if each_col_count > max_col{
max_col = each_col_count;
}
},
Ok(Event::Start(ref e)) if e.name().as_ref() == b"c" =>{
in_cell = true;
each_col_count +=1;
e.attributes().for_each(|a| {
let a = a.unwrap();
match a.key.as_ref(){
b"r" =>{
let reference = utils::attr_value(&a);
if let Ok((row, col)) = utils::reference2pos(reference.as_ref()) {
cell_row = row as usize;
cell_col = col as usize;
}
},
b"t" =>{
let t = utils::attr_value(&a) ;
if t == "s" || t=="str"{
is_string = true;
is_inlinstring = false;
}else if t=="n" {
is_string = false;
is_inlinstring = false;
}else if t=="inlineStr" {
is_string = true;
is_inlinstring = true;
}
},
b"s" =>{
let s = utils::attr_value(&a);
cell_format = *sheet_reader.styles.get(s.parse::<usize>().unwrap()).unwrap();
},
_ => {
println!("{:?}",a.key.as_ref());
}
}
});
},
Ok(Event::End(ref e)) if e.name().as_ref() == b"c" =>{
},
Ok(Event::Start(ref e)) if e.name().as_ref() == b"v" || e.name().as_ref() ==b"t"=>{
in_value = true;
},
Ok(Event::Text(ref e)) if in_value && in_cell =>{
in_value = false;
in_cell = false;
let raw_value = &e.unescape().unwrap()[..];
if is_string {
if is_inlinstring {
cells.push(
Cell{
pos: (cell_row, cell_col),
value: AnyValue::StringOwned(raw_value.to_owned().into()),
}
);
}else {
let s = sheet_reader.strings.get(raw_value.parse::<usize>().unwrap()).unwrap();
cells.push(
Cell{
pos: (cell_row, cell_col),
value: AnyValue::String(s.as_str()),
}
);
}
is_inlinstring = false;
is_string = false;
} else {
let num = raw_value.parse::<f64>().unwrap();
match cell_format {
CellFormat::Number =>{
cells.push(
Cell{
pos: (cell_row, cell_col),
value: AnyValue::Float64(num),
}
);
},
CellFormat::DateTime =>{
let gap_days = match sheet_reader.date_system {
DateSystem::V1900 => {
25569
},
DateSystem::V1904 => {
24109
}
};
cells.push(
Cell{
pos: (cell_row, cell_col),
value: AnyValue::Date(num as i32 - gap_days),
}
);
},
CellFormat::TimeDelta =>{
let gap_days = match sheet_reader.date_system {
DateSystem::V1900 => {
25569
},
DateSystem::V1904 => {
24109
}
};
let nanoseconds = ((num - gap_days as f64) *86400000.0) as i64;
cells.push(
Cell{
pos: (cell_row, cell_col),
value: AnyValue::Datetime(nanoseconds,TimeUnit::Milliseconds, None),
}
);
}
}
cell_format = CellFormat::Number;
}
},//ok text
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", sheet_reader.reader.buffer_position(), e),
_=> (),
}
buf.clear();
}//end of loop
let max_row = cells.last().unwrap().pos.0;
let len = max_col*max_row;
let mut range: Range<'_> = Range { cells: vec![Cell::new();len], max_col:max_col as usize};
for cell in cells {
let idx = (cell.pos.0-1) * max_col as usize + cell.pos.1 -1;
range.cells[idx] = cell;
}
range
}
/// Open an existing workbook (xlsx file). Returns a `Result` in case there is an error opening
/// the workbook.
///
/// # Example usage:
///
/// use xl::Workbook;
///
/// let mut wb = Workbook::open("tests/data/Book1.xlsx");
/// assert!(wb.is_ok());
///
/// // non-existant file
/// let mut wb = Workbook::open("Non-existant xlsx");
/// assert!(wb.is_err());
///
/// // non-xlsx file
/// let mut wb = Workbook::open("src/main.rs");
/// assert!(wb.is_err());
pub fn new(path: &str) -> Result<Self, String> {
if !std::path::Path::new(&path).exists() {
let err = format!("'{}' does not exist", &path);
return Err(err);
}
let zip_file = match fs::File::open(&path) {
Ok(z) => z,
Err(e) => return Err(e.to_string()),
};
match zip::ZipArchive::new(zip_file) {
Ok(mut xls) => {
let strings:Vec<String> = Vec::new();//strings2(&mut xls,3);//set read shared strings with 3 threads!
let styles = find_styles(&mut xls);
let date_system = get_date_system(&mut xls);
Ok(Workbook {
path: path.to_string(),
xls,
encoding: String::from("utf8"),
date_system,
strings,
styles,
threads: 1,//Default to single-thread
})
},
Err(e) => Err(e.to_string())
}
}
/// Alternative name for `Workbook::new`.
pub fn open(path: &str) -> Result<Self, String> { Workbook::new(path) }
/// Simple method to print out all the inner files of the xlsx zip.
pub fn contents(&mut self) {
for i in 0 .. self.xls.len() {
let file = self.xls.by_index(i).unwrap();
let outpath = match file.enclosed_name() {
Some(path) => path.to_owned(),
None => continue,
};
if (&*file.name()).ends_with('/') {
println!("File {}: \"{}\"", i, outpath.display());
} else {
println!(
"File {}: \"{}\" ({} bytes)",
i,
outpath.display(),
file.size()
);
}
}
}
/// Create a SheetReader for the given worksheet. A `SheetReader` is a struct in the
/// `xl::Worksheet` class that can be used to iterate over rows, etc. See documentation in the
/// `xl::Worksheet` module for more information.
pub fn sheet_reader<'a>(&'a mut self, zip_target: &str) -> SheetReader<'a> {
let mut target = match self.xls.by_name(zip_target) {
Ok(ws) => ws,
Err(_) => panic!("Cannot find the sheet: {}", zip_target),
};
let reader = BufReader::new(target);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
SheetReader::new(reader, &self.strings, &self.styles, &self.date_system)
}
pub fn sheet_reader2(&mut self, zip_target: &str) -> (Vec<u8>, Reader<BufReader<&'static [u8]>>) {
let mut target = match self.xls.by_name(zip_target) {
Ok(ws) => ws,
Err(_) => panic!("Cannot find the sheet: {}", zip_target),
};
// Copy the content of the target
let mut content = Vec::new();
target.read_to_end(&mut content).unwrap();
// Create a BufReader from the content
let content_static: &'static [u8] = Box::leak(content.into_boxed_slice());
let buf_reader = BufReader::new(content_static);
// Create a Reader from the BufReader
let mut reader = Reader::from_reader(buf_reader);
reader.config_mut().trim_text(true);
(content_static.to_vec(), reader)
}
}
fn strings2(zip_file: &mut ZipArchive<File>,threads_num:usize) -> Vec<String> {
let strings:Vec<String> =
match zip_file.by_name("xl/sharedStrings.xml") {
Ok(mut strings_file) => {
let mut data = Vec::new();
strings_file.read_to_end(&mut data).unwrap();
let chunker = utils::XmlChunker::new(&data, threads_num,"</si>");
let chunks = chunker.chunks();
let res: Vec<String> = chunks
.into_par_iter()
.flat_map(|chunk| {
let mut buf = Vec::with_capacity(1024);
let mut strings = Vec::with_capacity(1024);
let mut reader = quick_xml::Reader::from_str(&chunk);
let mut preserve_space = false;
let mut this_string = String::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.name() == QName(b"t") => {
preserve_space = utils::get_attribute(e.attributes(), b"xml:space")
.map_or(false, |att| att == "preserve");
},
Ok(Event::Text(ref e)) => this_string.push_str(&e.unescape().unwrap()[..]),
Ok(Event::Empty(ref e)) if e.name() == QName(b"t") => strings.push("".to_owned()),
Ok(Event::End(ref e)) if e.name() == QName(b"t") => {
if preserve_space {
strings.push(this_string.to_owned());
} else {
strings.push(this_string.trim().to_owned());
}
this_string.clear();
},
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
strings
})
.collect();
res
},
Err(_) => Vec::new(),
};
strings
}
fn strings(zip_file: &mut ZipArchive<File>) -> Vec<String> {
let mut strings = Vec::new();
match zip_file.by_name("xl/sharedStrings.xml") {
Ok(strings_file) => {
let reader = BufReader::new(strings_file);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut this_string = String::new();
let mut preserve_space = false;
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.name() == QName(b"t") => {
preserve_space = utils::get_attribute(e.attributes(), b"xml:space")
.map_or(false, |att| att == "preserve");
},
Ok(Event::Text(ref e)) => this_string.push_str(&e.unescape().unwrap()[..]),
Ok(Event::Empty(ref e)) if e.name() == QName(b"t") => strings.push("".to_owned()),
Ok(Event::End(ref e)) if e.name() == QName(b"t") => {
if preserve_space {
strings.push(this_string.to_owned());
} else {
strings.push(this_string.trim().to_owned());
}
this_string.clear();
},
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
strings
},
Err(_) => strings
}
}
/// find the number of rows and columns used in a particular worksheet. takes the workbook xlsx
/// location as its first parameter, and the location of the worksheet in question (within the zip)
/// as the second parameter. Returns a tuple of (rows, columns) in the worksheet.
fn find_styles(xlsx: &mut ZipArchive<fs::File>) -> Vec<CellFormat> {
let mut cell_farmats = Vec::new();
let mut number_formats = standard_styles();
let styles_xml = match xlsx.by_name("xl/styles.xml") {
Ok(s) => s,
Err(_) => return cell_farmats
};
// let _ = std::io::copy(&mut styles_xml, &mut std::io::stdout());
let reader = BufReader::new(styles_xml);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut record_styles = false;
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Empty(ref e)) if e.name() == QName(b"numFmt") => {
let id = utils::get_attribute(e.attributes(), b"numFmtId").unwrap();
let code = utils::get_attribute(e.attributes(), b"formatCode").unwrap();
number_formats.insert(id, code);
},
Ok(Event::Start(ref e)) if e.name() == QName(b"cellXfs") => {
record_styles = true;
},
Ok(Event::End(ref e)) if e.name() == QName(b"cellXfs") => record_styles = false,
Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e)) if record_styles && e.name() == QName(b"xf") => {
let id = utils::get_attribute(e.attributes(), b"numFmtId").unwrap();
cell_farmats.push(get_cell_format(&id));
},
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
cell_farmats
}
/// Return hashmap of standard styles (ISO/IEC 29500:2011 in Part 1, section 18.8.30)
fn standard_styles() -> HashMap<String, String> {
let mut styles = HashMap::new();
let standard_styles = [
["0", "General",],
["1", "0",],
["2", "0.00",],
["3", "#,##0",],
["4", "#,##0.00",],
["9", "0%",],
["10", "0.00%",],
["11", "0.00E+00",],
["12", "# ?/?",],
["13", "# ??/??",],
["14", "mm-dd-yy",],
["15", "d-mmm-yy",],
["16", "d-mmm",],
["17", "mmm-yy",],
["18", "h:mm AM/PM",],
["19", "h:mm:ss AM/PM",],
["20", "h:mm",],
["21", "h:mm:ss",],
["22", "m/d/yy h:mm",],
["37", "#,##0 ;(#,##0)",],
["38", "#,##0 ;[Red](#,##0)",],
["39", "#,##0.00;(#,##0.00)",],
["40", "#,##0.00;[Red](#,##0.00)",],
["45", "mm:ss",],
["46", "[h]:mm:ss",],
["47", "mmss.0",],
["48", "##0.0E+0",],
["49", "@",],
];
for style in standard_styles {
let [id, code] = style;
styles.insert(id.to_string(), code.to_string());
}
styles
}
fn get_date_system(xlsx: &mut ZipArchive<fs::File>) -> DateSystem {
match xlsx.by_name("xl/workbook.xml") {
Ok(wb) => {
let reader = BufReader::new(wb);
let mut reader = Reader::from_reader(reader);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Empty(ref e)) if e.name() == QName(b"workbookPr") => {
if let Some(system) = utils::get_attribute(e.attributes(), b"date1904") {
if system == "1" {
break DateSystem::V1904
}
}
break DateSystem::V1900
},
Ok(Event::Eof) => break DateSystem::V1900,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
},
Err(_) => panic!("Could not find xl/workbook.xml")
}
}