Skip to main content

nu_command/formats/from/
xlsx.rs

1use calamine::{Reader, Sheets, Xlsx};
2
3use super::sheets::{collect_binary, common_sheets_signature, from_sheets};
4use nu_engine::command_prelude::*;
5
6#[derive(Clone)]
7pub struct FromXlsx;
8
9impl Command for FromXlsx {
10    fn name(&self) -> &str {
11        "from xlsx"
12    }
13
14    fn signature(&self) -> Signature {
15        common_sheets_signature("from xlsx")
16    }
17
18    fn description(&self) -> &str {
19        "Parse binary Excel(.xlsx) data and create table."
20    }
21
22    fn run(
23        &self,
24        engine_state: &EngineState,
25        stack: &mut Stack,
26        call: &Call,
27        mut input: PipelineData,
28    ) -> Result<PipelineData, ShellError> {
29        let head = call.head;
30        let metadata = input.take_metadata().map(|md| md.with_content_type(None));
31
32        let input_span = input.span().unwrap_or(head);
33        let reader = collect_binary(input, head)?;
34        let xlsx = Xlsx::new(reader).map_err(|_| ShellError::UnsupportedInput {
35            msg: "Could not load XLSX file".to_string(),
36            input: "value originates from here".into(),
37            msg_span: head,
38            input_span,
39        })?;
40        let sheets = Sheets::Xlsx(xlsx);
41
42        from_sheets(sheets, input_span, engine_state, stack, call)
43            .map(|pd| pd.set_metadata(metadata))
44    }
45
46    fn examples(&self) -> Vec<Example<'_>> {
47        vec![
48            Example {
49                description: "Convert binary .xlsx data to a table.",
50                example: "open --raw test.xlsx | from xlsx",
51                result: None,
52            },
53            Example {
54                description: "Convert binary .xlsx data to a table, specifying the tables.",
55                example: "open --raw test.xlsx | from xlsx --sheets [Spreadsheet1]",
56                result: None,
57            },
58            Example {
59                description: "Convert binary .xlsx data to a table, specifying the tables and specifying no header row.",
60                example: "open --raw test.xlsx | from xlsx --sheets [Spreadsheet1] --noheaders",
61                result: None,
62            },
63        ]
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn test_examples() -> nu_test_support::Result {
73        nu_test_support::test().examples(FromXlsx)
74    }
75}