xls-rs 0.1.6

A powerful CLI tool and library for spreadsheet manipulation with pandas-style operations. Supports CSV, Excel (XLSX, XLS, ODS), Parquet, and Avro formats with formula evaluation, data transformation, and comprehensive analytics capabilities.
Documentation
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
//! Excel feature detection and structured errors
//!
//! This module provides utilities for detecting Excel features that may not be fully supported
//! and returns structured error messages with actionable guidance.

use anyhow::{anyhow, Result};
use regex::Regex;
use std::io::Read;

/// Unsupported Excel feature with structured error information
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnsupportedFeature {
    /// Merged cells (partial support - cells are read but merge status is lost)
    MergedCells {
        sheet: String,
        range: String,
    },
    /// Pivot tables (not supported - data may be read but pivot structure is lost)
    PivotTable {
        sheet: String,
    },
    /// Data validation (not supported - data is readable but validation rules are lost)
    DataValidation {
        sheet: String,
        range: String,
    },
    /// Conditional formatting (read-only - formats are visible but not editable)
    ConditionalFormatting {
        sheet: String,
    },
    /// Array formulas (limited support - formulas may be read as static values)
    ArrayFormulas {
        sheet: String,
    },
    /// Protected sheets (read-only - content readable but cannot be modified)
    ProtectedSheet {
        sheet: String,
        password_protected: bool,
    },
    /// External references/links (not supported - references may be broken)
    ExternalReferences {
        sheet: String,
    },
    /// Charts (read-only - data visible but chart configuration is lost)
    Charts {
        sheet: String,
        count: usize,
    },
    /// Images/Objects (not supported - visual elements are lost)
    EmbeddedObjects {
        sheet: String,
        object_type: String,
    },
}

impl UnsupportedFeature {
    /// Get a user-friendly description of the unsupported feature
    pub fn description(&self) -> String {
        match self {
            Self::MergedCells { sheet, range } => {
                format!(
                    "Merged cells detected in sheet '{}' range '{}'. Merged cells will be read as individual cells. Merge structure will be lost on write.",
                    sheet, range
                )
            }
            Self::PivotTable { sheet } => {
                format!(
                    "Pivot table detected in sheet '{}'. Pivot tables are not fully supported - data will be read as static values. Pivot structure, filters, and calculations will be lost.",
                    sheet
                )
            }
            Self::DataValidation { sheet, range } => {
                format!(
                    "Data validation detected in sheet '{}' range '{}'. Validation rules will be lost when modifying or writing this file.",
                    sheet, range
                )
            }
            Self::ConditionalFormatting { sheet } => {
                format!(
                    "Conditional formatting detected in sheet '{}'. Formatting rules will be preserved on read but may not be editable through xls-rs.",
                    sheet
                )
            }
            Self::ArrayFormulas { sheet } => {
                format!(
                    "Array formulas detected in sheet '{}'. Array formulas may be read as static values. Dynamic calculation behavior may be lost.",
                    sheet
                )
            }
            Self::ProtectedSheet { sheet, password_protected } => {
                if *password_protected {
                    format!(
                        "Sheet '{}' is password protected. Content is readable but cannot be modified. Remove protection to enable editing.",
                        sheet
                    )
                } else {
                    format!(
                        "Sheet '{}' is protected. Content is readable but editing may be limited.",
                        sheet
                    )
                }
            }
            Self::ExternalReferences { sheet } => {
                format!(
                    "External references detected in sheet '{}'. External links may be broken or not accessible. Consider consolidating data.",
                    sheet
                )
            }
            Self::Charts { sheet, count } => {
                format!(
                    "Charts detected in sheet '{}' ({} chart(s)). Charts are read-only through xls-rs - data is visible but chart configuration cannot be modified.",
                    sheet, count
                )
            }
            Self::EmbeddedObjects { sheet, object_type } => {
                format!(
                    "Embedded {} detected in sheet '{}'. Visual elements like images and shapes are not fully supported - they may be lost on read/write.",
                    object_type, sheet
                )
            }
        }
    }

    /// Get the severity level of the unsupported feature
    pub fn severity(&self) -> FeatureSeverity {
        match self {
            Self::MergedCells { .. } => FeatureSeverity::Warning,
            Self::PivotTable { .. } => FeatureSeverity::Limitation,
            Self::DataValidation { .. } => FeatureSeverity::Warning,
            Self::ConditionalFormatting { .. } => FeatureSeverity::Warning,
            Self::ArrayFormulas { .. } => FeatureSeverity::Limitation,
            Self::ProtectedSheet { password_protected: true, .. } => FeatureSeverity::Error,
            Self::ProtectedSheet { password_protected: false, .. } => FeatureSeverity::Warning,
            Self::ExternalReferences { .. } => FeatureSeverity::Warning,
            Self::Charts { .. } => FeatureSeverity::Warning,
            Self::EmbeddedObjects { .. } => FeatureSeverity::Limitation,
        }
    }

    /// Get actionable guidance for working around the limitation
    pub fn guidance(&self) -> Option<String> {
        match self {
            Self::MergedCells { .. } => Some(
                "To preserve merged cells, consider using Excel directly or exporting to a format that maintains merge structure.".to_string()
            ),
            Self::PivotTable { .. } => Some(
                "For full pivot table support, use Excel directly. To work with pivot data, consider flattening the pivot table to static values first.".to_string()
            ),
            Self::DataValidation { .. } => Some(
                "Data validation rules can be re-applied after modification using the conditional-format command.".to_string()
            ),
            Self::ProtectedSheet { password_protected: true, .. } => Some(
                "Unprotect the sheet in Excel with the password to enable full editing capabilities.".to_string()
            ),
            Self::ExternalReferences { .. } => Some(
                "Replace external references with static values or consolidate external data into the workbook.".to_string()
            ),
            _ => None,
        }
    }

    /// Convert to an anyhow::Error with full context
    pub fn to_error(&self) -> anyhow::Error {
        let desc = self.description();
        let severity = self.severity();
        let guidance = self.guidance();

        let msg = if let Some(g) = guidance {
            format!("[{}] {}. Guidance: {}", severity, desc, g)
        } else {
            format!("[{}] {}", severity, desc)
        };

        anyhow!(msg)
    }
}

/// Severity level of unsupported features
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FeatureSeverity {
    /// Informational - feature is read-only but functional
    Info,
    /// Warning - feature has limited support but data is preserved
    Warning,
    /// Limitation - feature is partially supported with some data loss
    Limitation,
    /// Error - feature prevents the operation from completing
    Error,
}

impl std::fmt::Display for FeatureSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FeatureSeverity::Info => write!(f, "INFO"),
            FeatureSeverity::Warning => write!(f, "WARNING"),
            FeatureSeverity::Limitation => write!(f, "LIMITATION"),
            FeatureSeverity::Error => write!(f, "ERROR"),
        }
    }
}

/// Excel file feature detector
///
/// This struct provides methods to detect potentially unsupported features
/// in Excel files before attempting operations that may fail or lose data.
pub struct FeatureDetector;

impl FeatureDetector {
    /// Detect features that may affect read/write operations.
    ///
    /// For `.xlsx`, the zip bundle is scanned (`xl/workbook.xml`, `xl/worksheets/*.xml`,
    /// `xl/charts/*.xml`). Other extensions keep [`Self::heuristic_check`] only.
    pub fn detect_potential_issues(path: &str) -> Result<Vec<UnsupportedFeature>> {
        let mut issues = Self::heuristic_check(path);
        if !path.to_lowercase().ends_with(".xlsx") {
            return Ok(issues);
        }

        let file = std::fs::File::open(path).map_err(|e| anyhow!(e))?;
        let mut archive = zip::ZipArchive::new(file).map_err(|e| anyhow!(e))?;
        let mut workbook_xml = String::new();
        {
            let mut e = archive
                .by_name("xl/workbook.xml")
                .map_err(|_| anyhow!("invalid xlsx: missing xl/workbook.xml"))?;
            e.read_to_string(&mut workbook_xml)
                .map_err(|e| anyhow!(e))?;
        }
        let re_name = Regex::new(r#"<sheet[^>]+name="([^"]+)""#).expect("sheet name regex");
        let sheet_names: Vec<String> = re_name
            .captures_iter(&workbook_xml)
            .map(|c| c[1].to_string())
            .collect();

        let re_sheet_num = Regex::new(r"sheet(\d+)\.xml$").expect("sheet file regex");
        let ref_cell = Regex::new(r#"ref="([^"]+)""#).expect("ref attr regex");
        let ref_sq = Regex::new(r#"sqref="([^"]+)""#).expect("sqref attr regex");
        let mut chart_count: usize = 0;

        for i in 0..archive.len() {
            let mut entry = archive.by_index(i).map_err(|e| anyhow!(e))?;
            let ename = entry.name().to_string();
            if ename.starts_with("xl/charts/chart") && ename.ends_with(".xml") {
                chart_count += 1;
                continue;
            }
            if !ename.starts_with("xl/worksheets/") || !ename.ends_with(".xml") {
                continue;
            }
            let mut data = String::new();
            entry
                .read_to_string(&mut data)
                .map_err(|e| anyhow!(e))?;

            let sheet_idx = re_sheet_num
                .captures(&ename)
                .and_then(|c| c[1].parse::<usize>().ok())
                .unwrap_or(1);
            let sheet = sheet_names
                .get(sheet_idx.saturating_sub(1))
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());

            if data.contains("mergeCells") || data.contains("mergeCell") {
                let range = ref_cell
                    .captures(&data)
                    .map(|c| c[1].to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                issues.push(UnsupportedFeature::MergedCells {
                    sheet: sheet.clone(),
                    range,
                });
            }
            if data.contains("pivotCache") || data.contains("pivotTable") {
                issues.push(UnsupportedFeature::PivotTable { sheet: sheet.clone() });
            }
            if data.contains("dataValidation") {
                let range = ref_sq
                    .captures(&data)
                    .map(|c| c[1].to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                issues.push(UnsupportedFeature::DataValidation {
                    sheet: sheet.clone(),
                    range,
                });
            }
            if data.contains("conditionalFormatting") {
                issues.push(UnsupportedFeature::ConditionalFormatting {
                    sheet: sheet.clone(),
                });
            }
            if data.contains("sheetProtection") {
                let password_protected = data.contains("password");
                issues.push(UnsupportedFeature::ProtectedSheet {
                    sheet,
                    password_protected,
                });
            }
        }

        if chart_count > 0 {
            let sheet = sheet_names
                .first()
                .cloned()
                .unwrap_or_else(|| "unknown".to_string());
            issues.push(UnsupportedFeature::Charts {
                sheet,
                count: chart_count,
            });
        }

        Ok(issues)
    }

    /// Check if a file is likely to contain unsupported features
    ///
    /// This is a heuristic check based on file extension and size.
    /// Complex Excel files (large, multiple sheets) are more likely
    /// to have unsupported features.
    pub fn heuristic_check(path: &str) -> Vec<UnsupportedFeature> {
        let mut issues = Vec::new();

        let path_lower = path.to_lowercase();

        // Check for very large files (more likely to have complex features)
        if let Ok(metadata) = std::fs::metadata(path) {
            if metadata.len() > 10 * 1024 * 1024 {
                // File > 10MB
                issues.push(UnsupportedFeature::PivotTable {
                    sheet: "unknown".to_string(),
                });
            }
        }

        // ODS files have different feature set
        if path_lower.ends_with(".ods") {
            // ODS may have different limitations
        }

        issues
    }

    /// Validate that a file doesn't contain features that would prevent write operations
    pub fn validate_for_write(path: &str) -> Result<()> {
        // Check for potential issues
        let issues = Self::detect_potential_issues(path)?;

        // Filter to only error-level issues for write validation
        let errors: Vec<_> = issues
            .into_iter()
            .filter(|f| f.severity() == FeatureSeverity::Error)
            .collect();

        if !errors.is_empty() {
            let error_messages: Vec<String> = errors
                .iter()
                .map(|f| f.description())
                .collect();
            return Err(anyhow!(
                "File contains features that prevent write operations:\n{}",
                error_messages.join("\n")
            ));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unsupported_feature_description() {
        let feature = UnsupportedFeature::MergedCells {
            sheet: "Sheet1".to_string(),
            range: "A1:B2".to_string(),
        };
        let desc = feature.description();
        assert!(desc.contains("Merged cells"));
        assert!(desc.contains("Sheet1"));
        assert!(desc.contains("A1:B2"));
    }

    #[test]
    fn test_feature_severity() {
        assert_eq!(
            UnsupportedFeature::MergedCells {
                sheet: "S".to_string(),
                range: "A1".to_string(),
            }
            .severity(),
            FeatureSeverity::Warning
        );

        assert_eq!(
            UnsupportedFeature::ProtectedSheet {
                sheet: "S".to_string(),
                password_protected: true,
            }
            .severity(),
            FeatureSeverity::Error
        );
    }

    #[test]
    fn test_to_error() {
        let feature = UnsupportedFeature::PivotTable {
            sheet: "Sheet1".to_string(),
        };
        let error = feature.to_error();
        assert!(error.to_string().contains("Pivot table"));
    }

    #[test]
    fn detect_simple_written_xlsx_has_no_error_severity_flags() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("t.xlsx");
        let handler = crate::ExcelHandler::new();
        let data = vec![vec!["a".to_string()]];
        handler
            .write_styled(
                p.to_str().unwrap(),
                &data,
                &crate::WriteOptions::default(),
            )
            .unwrap();
        let issues = FeatureDetector::detect_potential_issues(p.to_str().unwrap()).unwrap();
        let errors: Vec<_> = issues
            .iter()
            .filter(|i| i.severity() == FeatureSeverity::Error)
            .collect();
        assert!(
            errors.is_empty(),
            "expected no error-level workbook features, got {errors:?}"
        );
    }
}