mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-22 13:58:28 -06:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e186c6811 | ||
|
|
586abdadd2 | ||
|
|
98ba4e989a |
+42
-17
@@ -8,6 +8,7 @@ use gridcraft_core::{CellError, CellRef, RangeRef, Value};
|
||||
use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook};
|
||||
|
||||
use crate::package::MAX_ENTRIES;
|
||||
use crate::read::SheetNames;
|
||||
use crate::{IoError, ReadReport};
|
||||
|
||||
const MIME: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet";
|
||||
@@ -32,6 +33,10 @@ pub(crate) fn has_mimetype(bytes: &[u8]) -> bool {
|
||||
/// imported as constants, so editing their inputs does not recalculate the original formula.
|
||||
/// Always inspect the returned warnings. Saving to ODS is not supported.
|
||||
pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
// The exact mimetype, as `sniff` requires: craft-ods alone accepts some near misses.
|
||||
if !has_mimetype(bytes) {
|
||||
return Err(IoError::Format("missing or invalid ODS mimetype".into()));
|
||||
}
|
||||
let book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?;
|
||||
if book.sheets.is_empty() {
|
||||
return Err(IoError::Format("ODS contains no worksheets".into()));
|
||||
@@ -40,7 +45,10 @@ pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into()));
|
||||
}
|
||||
|
||||
// `Workbook::new` starts with an empty Sheet1; the ODS tables are the only sheets.
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.clear();
|
||||
let mut names = SheetNames::default();
|
||||
let mut report = ReadReport::default();
|
||||
report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported.");
|
||||
|
||||
@@ -48,32 +56,49 @@ pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
|
||||
let mut warned_unavailable = false;
|
||||
|
||||
for src_sheet in book.sheets {
|
||||
let mut sheet = Sheet::new(&src_sheet.name);
|
||||
let mut name = names.unique(src_sheet.name.trim_matches('\''), wb.sheets.len());
|
||||
if wb.check_sheet_name(&name, None).is_err() {
|
||||
name = wb.next_sheet_name();
|
||||
names.insert(&name);
|
||||
}
|
||||
let mut sheet = Sheet::new(name);
|
||||
if !warned_rename && sheet.name != src_sheet.name {
|
||||
warned_rename = true;
|
||||
report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names.");
|
||||
}
|
||||
|
||||
for (coord, src_cell) in src_sheet.cells {
|
||||
let value = match src_cell.value() {
|
||||
Some(v) => map_value(v),
|
||||
None if src_cell.formula.is_some() => {
|
||||
if !warned_unavailable {
|
||||
warned_unavailable = true;
|
||||
report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
|
||||
}
|
||||
Value::Text(Arc::from("[Unavailable ODS formula result]"))
|
||||
// A typed value that cannot be read (an unparsable number or date, an error cache,
|
||||
// a formula without a result) keeps what the cell showed, else its raw value.
|
||||
let Some(value) = src_cell.value().map(map_value) else {
|
||||
if !warned_unavailable {
|
||||
warned_unavailable = true;
|
||||
report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result].");
|
||||
}
|
||||
None => continue,
|
||||
let text = if !src_cell.text.is_empty() {
|
||||
src_cell.text.as_str()
|
||||
} else if let Some(raw) = src_cell.raw.as_deref() {
|
||||
raw
|
||||
} else if src_cell.formula.is_some() {
|
||||
"[Unavailable ODS formula result]"
|
||||
} else {
|
||||
"[Unsupported ODS value]"
|
||||
};
|
||||
sheet.set_cell(CellRef::new(coord.row, coord.col), Cell::styled(Value::Text(Arc::from(text)), StyleId::DEFAULT));
|
||||
continue;
|
||||
};
|
||||
|
||||
let style_id = match src_cell.value_type {
|
||||
Some(craft_ods::ValueType::Date) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("yyyy-mm-dd")),
|
||||
Some(craft_ods::ValueType::Time) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("[h]:mm:ss")),
|
||||
Some(craft_ods::ValueType::Percentage) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("0.00%")),
|
||||
Some(craft_ods::ValueType::Currency) => wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new("#,##0.00")),
|
||||
_ => StyleId::DEFAULT,
|
||||
let format = match src_cell.value_type {
|
||||
Some(craft_ods::ValueType::Date) => {
|
||||
let with_time = src_cell.raw.as_deref().and_then(craft_ods::date_serial).is_some_and(|(_, time)| time);
|
||||
Some(if with_time { "yyyy-mm-dd hh:mm:ss.000" } else { "yyyy-mm-dd" })
|
||||
}
|
||||
Some(craft_ods::ValueType::Time) => Some("[h]:mm:ss.000"),
|
||||
Some(craft_ods::ValueType::Percentage) => Some("0.00%"),
|
||||
Some(craft_ods::ValueType::Currency) => Some("#,##0.00"),
|
||||
_ => None,
|
||||
};
|
||||
let style_id = format.map_or(StyleId::DEFAULT, |code| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)));
|
||||
|
||||
let target_coord = CellRef::new(coord.row, coord.col);
|
||||
sheet.set_cell(target_coord, Cell::styled(value, style_id));
|
||||
@@ -103,7 +128,7 @@ fn map_value(v: craft_ods::Value) -> Value {
|
||||
match v {
|
||||
craft_ods::Value::Empty => Value::Empty,
|
||||
craft_ods::Value::Number(n) => Value::Number(n),
|
||||
craft_ods::Value::Text(s) => Value::Text(Arc::from(s)),
|
||||
craft_ods::Value::Text(s) => Value::Text(s),
|
||||
craft_ods::Value::Bool(b) => Value::Bool(b),
|
||||
craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)),
|
||||
}
|
||||
|
||||
@@ -111,6 +111,19 @@ fn ods_repeats_merges_sheet_names_and_empty_tail_remain_sparse() {
|
||||
assert_eq!(wb.sheets[1].value(CellRef::new(0, 0)), text("second sheet"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_tables_are_the_only_sheets_with_unique_valid_names() {
|
||||
let cell = r#"<table:table-row><table:table-cell office:value-type="float" office:value="1"/></table:table-row>"#;
|
||||
let bytes = ods(&format!(
|
||||
r#"<table:table table:name="Data">{cell}</table:table><table:table table:name="data">{cell}</table:table><table:table table:name="a/b">{cell}</table:table>"#
|
||||
));
|
||||
let (wb, report) = read_ods(&bytes).unwrap();
|
||||
let names: Vec<&str> = wb.sheets.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Data", "data (2)", "ab"]);
|
||||
assert!(wb.sheets.iter().all(|s| s.value(CellRef::new(0, 0)) == Value::Number(1.0)));
|
||||
assert!(report.warnings.iter().any(|w| w.contains("renamed")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_dates_and_durations_use_formats_and_unsupported_values_stay_text() {
|
||||
let bytes = row(r#"
|
||||
@@ -158,8 +171,8 @@ fn ods_rejects_bad_packages_encryption_and_truncated_xml() {
|
||||
for mime in [b"application/zip".as_slice(), b"application/vnd.oasis.opendocument.spreadsheet "] {
|
||||
assert!(read_ods(&make_zip(&[("mimetype", mime), ("content.xml", xml.as_bytes())])).is_err());
|
||||
}
|
||||
let encrypted =
|
||||
br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:encryption-data/></manifest:manifest>"#;
|
||||
// As LibreOffice writes it: the encryption data belongs to the encrypted file's entry.
|
||||
let encrypted = br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"><manifest:encryption-data manifest:checksum-type="SHA1/1K" manifest:checksum="AAAA"/></manifest:file-entry></manifest:manifest>"#;
|
||||
assert!(
|
||||
read_ods(&make_zip(&[("mimetype", MIME), ("META-INF/manifest.xml", encrypted), ("content.xml", xml.as_bytes())]))
|
||||
.unwrap_err()
|
||||
|
||||
Reference in New Issue
Block a user