Skip to main content

teaql_tool_extra/
excel.rs

1use teaql_tool_core::{Result, TeaQLToolError};
2use rust_xlsxwriter::Workbook;
3use calamine::{Reader, open_workbook_auto};
4
5#[derive(Debug, Clone)]
6pub struct ExcelTool;
7
8impl ExcelTool {
9    pub fn new() -> Self { Self }
10
11    pub fn write_simple(&self, path: &str, data: &[Vec<String>]) -> Result<()> {
12        let mut workbook = Workbook::new();
13        let worksheet = workbook.add_worksheet();
14        
15        for (row, r_data) in data.iter().enumerate() {
16            for (col, val) in r_data.iter().enumerate() {
17                worksheet.write_string(row as u32, col as u16, val).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
18            }
19        }
20        
21        workbook.save(path).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
22        Ok(())
23    }
24
25    pub fn read_simple(&self, path: &str) -> Result<Vec<Vec<String>>> {
26        let mut workbook = open_workbook_auto(path).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
27        let sheet_name = workbook.sheet_names().get(0).cloned().unwrap_or_default();
28        if let Ok(range) = workbook.worksheet_range(&sheet_name) {
29            let mut result = Vec::new();
30            for row in range.rows() {
31                let row_data: Vec<String> = row.iter().map(|c| c.to_string()).collect();
32                result.push(row_data);
33            }
34            Ok(result)
35        } else {
36            Ok(Vec::new())
37        }
38    }
39}
40
41impl Default for ExcelTool {
42    fn default() -> Self { Self::new() }
43}