Skip to main content

excel_rs/
workbook.rs

1use super::format::XlsxFormatter;
2use crate::error::{ExcelError, Result};
3use std::{
4    collections::HashSet,
5    io::{Seek, Write},
6};
7use zip::ZipWriter;
8
9use super::sheet::Sheet;
10
11/// A WorkBook represents one excel file.
12pub struct WorkBook<W: Write + Seek> {
13    formatter: XlsxFormatter<W>,
14    sheet_names: HashSet<String>,
15}
16
17impl<W: Write + Seek> WorkBook<W> {
18    /// Create a new WorkBook. `writer` is the destination to write the excel file to
19    pub fn new(writer: W) -> Self {
20        let zip_writer = ZipWriter::new(writer);
21
22        WorkBook {
23            formatter: XlsxFormatter::new(zip_writer),
24            sheet_names: HashSet::new(),
25        }
26    }
27
28    /// Creates a new Sheet with the given name.
29    pub fn new_worksheet<'a>(&'a mut self, name: String) -> Result<Sheet<'a, W>> {
30        if self.sheet_names.len() == crate::MAX_SHEETS {
31            return Err(ExcelError::TooManySheets);
32        }
33
34        if self.sheet_names.contains(&name) {
35            return Err(ExcelError::SheetAlreadyExists);
36        }
37
38        let id = self.sheet_names.len() as u16 + 1;
39        self.sheet_names.insert(name.clone());
40        Sheet::new(name, id, &mut self.formatter.zip_writer)
41    }
42
43    /// Finish writing to the excel file. This closes the file and wraps up any remaining operations.
44    pub fn finish(self) -> Result<W> {
45        self.formatter
46            .finish(self.sheet_names.into_iter().collect::<Vec<String>>())
47    }
48}