Merge pull request #2270 from vedran-dobos/csv-sep-line

CSV: an Excel `sep=` first line names the delimiter (#1446)
This commit is contained in:
FredApps
2026-11-26 23:10:07 +01:00
committed by GitHub
7 changed files with 339 additions and 17 deletions
+10 -4
View File
@@ -532,8 +532,8 @@ pub fn save_bytes_as(wb: &Workbook, path: &str, kind: FileKind) -> Result<Vec<u8
Err(EngineError::Other("SYLK (.slk) is supported for import only. Save as .xlsx or another supported export format.".into()))
}
// A workbook read from CSV keeps the separator it was read with (a `;` file stays `;`).
FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, wb.csv_delimiter.unwrap_or(b','))).transpose().map(Option::unwrap_or_default),
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, b'\t')).transpose().map(Option::unwrap_or_default),
FileKind::Csv => wb.sheet(sheet).map(|sh| csv(wb, sh, Some(wb.csv_delimiter.unwrap_or(b',')))).transpose().map(Option::unwrap_or_default),
FileKind::Tsv => wb.sheet(sheet).map(|sh| csv(wb, sh, None)).transpose().map(Option::unwrap_or_default),
FileKind::Json => crate::macros::json_bytes(wb),
FileKind::Html => to_html(wb, sheet).map(String::into_bytes),
}
@@ -567,8 +567,14 @@ pub fn source_path(path: &str) -> Option<std::path::PathBuf> {
/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as
/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers
/// that `&` writes in scientific notation as their 15 digits in full.
fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result<Vec<u8>> {
gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string()))
/// `delimiter` `None` writes a tab-separated file (`.tsv`, `.txt`).
fn csv(wb: &Workbook, sh: &Sheet, delimiter: Option<u8>) -> Result<Vec<u8>> {
let text = |c| crate::display::value_text(wb, sh, c);
match delimiter {
Some(d) => gridcraft_xlsx::write_csv(sh, d, text),
None => gridcraft_xlsx::write_tsv(sh, text),
}
.map_err(|e| EngineError::Other(e.to_string()))
}
/// The active sheet as CSV of raw cell values, for automation: numbers at full precision, dates and
+58
View File
@@ -518,6 +518,64 @@ fn csv_save_keeps_the_separator_it_was_opened_with() {
assert_eq!(String::from_utf8(save_bytes(&wb, "tabs.csv").unwrap()).unwrap(), tabs);
}
/// #1446: File › Open honours Excel's `sep=` first line; saved again, the file opens in the same
/// columns. A `.txt` file is read with tabs, so its `sep=` line stays data.
#[test]
fn csv_open_honours_a_sep_line_and_saves_a_file_that_reopens_in_columns() {
let (wb, _) = open_bytes("parts.csv", b"sep=|\r\nPart|Note\r\n1|a,b\r\n").unwrap();
let sh = wb.sheet(0).unwrap();
let text = |a: &str| sh.value(CellRef::parse(a).unwrap()).as_text().map(str::to_string);
assert_eq!((text("A1"), text("B1"), text("B2")), (Some("Part".into()), Some("Note".into()), Some("a,b".into())));
let saved = save_bytes(&wb, "parts.csv").unwrap();
assert_eq!(String::from_utf8(saved.clone()).unwrap(), "Part,Note\r\n1,\"a,b\"\r\n");
let (again, _) = open_bytes("parts.csv", &saved).unwrap();
assert_eq!(again.sheet(0).unwrap().value(CellRef::parse("B2").unwrap()).as_text(), Some("a,b"));
// `sep=;` keeps its semicolons, as a semicolon file does.
let (semi, _) = open_bytes("semi.csv", b"sep=;\r\na;b\r\n").unwrap();
assert_eq!(save_bytes(&semi, "semi.csv").unwrap(), b"a;b\r\n");
let (txt, _) = open_bytes("list.txt", b"sep=|\r\na\tb\r\n").unwrap();
assert_eq!(txt.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=|"));
}
/// A first cell that reads like a `sep=` line needs one of its own only in a CSV. A `.tsv` is read
/// with tabs given, so a `sep=` line there would come back as an extra row above the data.
#[test]
fn csv_save_names_its_delimiter_when_reopening_would_pick_another() {
let cells = |wb: &Workbook| {
let sh = wb.sheet(0).unwrap();
(0..2).map(|c| sh.value(CellRef::new(0, c)).as_text().map(str::to_string)).collect::<Vec<_>>()
};
// Read with `;`; saved, `a,b` loses its quotes and the line has one comma and one semicolon,
// which detection alone would read as comma-separated.
let (wb, _) = open_bytes("tie.csv", b"sep=;\r\n\"a,b\";x\r\n").unwrap();
let saved = save_bytes(&wb, "tie.csv").unwrap();
assert_eq!(saved, b"sep=;\r\na,b;x\r\n");
assert_eq!(cells(&open_bytes("tie.csv", &saved).unwrap().0), [Some("a,b".into()), Some("x".into())]);
// `|` is saved as commas; semicolons in the values would make detection pick `;`.
let (wb, _) = open_bytes("pipe.csv", b"sep=|\r\na;b;c|d;e;f\r\n").unwrap();
let saved = save_bytes(&wb, "pipe.csv").unwrap();
assert_eq!(saved, b"sep=,\r\na;b;c,d;e;f\r\n");
assert_eq!(cells(&open_bytes("pipe.csv", &saved).unwrap().0), [Some("a;b;c".into()), Some("d;e;f".into())]);
}
#[test]
fn tsv_save_writes_no_sep_line_and_reopens_in_place() {
let mut wb = Workbook::new();
let sh = wb.sheet_mut(0).unwrap();
sh.set_value(CellRef::new(0, 0), gridcraft_core::Value::text("sep=;"));
sh.set_value(CellRef::new(1, 0), gridcraft_core::Value::text("x"));
let saved = save_bytes(&wb, "list.tsv").unwrap();
assert_eq!(saved, b"sep=;\r\nx\r\n");
let (again, _) = open_bytes("list.tsv", &saved).unwrap();
let text = |r: u32| again.sheet(0).unwrap().value(CellRef::new(r, 0)).as_text().map(str::to_string);
assert_eq!((text(0), text(1)), (Some("sep=;".into()), Some("x".into())));
// Saved as CSV, the same sheet keeps its protective line, which reading drops again.
let csv = save_bytes(&wb, "list.csv").unwrap();
assert_eq!(csv, b"sep=,\r\nsep=;\r\nx\r\n");
let (again, _) = open_bytes("list.csv", &csv).unwrap();
assert_eq!(again.sheet(0).unwrap().value(CellRef::new(0, 0)).as_text(), Some("sep=;"));
}
#[test]
fn csv_save_of_a_workbook_not_read_from_csv_uses_commas() {
let mut wb = Workbook::new();
+121 -10
View File
@@ -16,11 +16,73 @@ pub const MAX_CSV_BYTES: usize = 512 << 20;
pub use craft_csv::{decode_text, sniff_delimiter};
/// Excel's `sep=` line: a first line `sep=` plus one character names the delimiter and isn't data.
/// Returns the delimiter it names (`None`: the line names none, so nothing is split) and the bytes
/// to skip, line end included. Observed in Excel 16.0 (build 17932, Windows): spaces anywhere in the
/// line are ignored, `SEP=` is the same, the line may be quoted as a whole field, and `sep=` with
/// nothing after it (or a non-ASCII character) is dropped and splits nothing. Two characters after
/// `=` (a tab counts: `sep=|<tab>`), or the line anywhere but first, is data.
pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option<char>, usize)> {
let end = text.find(['\r', '\n']).unwrap_or(text.len());
let skip = match text.get(end..end + 2) {
Some("\r\n") => end + 2,
_ if end < text.len() => end + 1,
_ => end,
};
let line: String = text.get(..end)?.chars().filter(|&c| c != ' ').collect();
let line = line.strip_prefix(quote).and_then(|l| l.strip_suffix(quote)).unwrap_or(&line);
let rest = line.get(..4).filter(|p| p.eq_ignore_ascii_case("sep=")).and_then(|_| line.get(4..))?;
let mut chars = rest.chars();
match (chars.next(), chars.next()) {
(None, _) => Some((None, skip)),
(Some(c), None) => Some((Some(c).filter(char::is_ascii), skip)),
_ => None,
}
}
/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields.
fn parse_records(text: &str, delim: char, quote: char, on_record: impl FnMut(Vec<String>) -> bool) {
craft_csv::parse_records(text, delim, quote, MAX_COLS as usize, on_record);
}
/// The delimiter and quote character to read `text` with. craft-csv always splits and unquotes, so
/// for a `sep=` line that names no delimiter (each line is one field) or names the quote (nothing is
/// quoted), a character `text` doesn't hold stands in: a Unicode noncharacter (U+FDD0 to U+FDEF,
/// which exchanged text doesn't use), else any other. A text that holds every character leaves
/// none, and is refused rather than split at one of its own.
fn stand_ins(text: &str, delim: Option<char>, quote: Option<char>) -> Result<(char, char), IoError> {
if let (Some(d), Some(q)) = (delim, quote) {
return Ok((d, q));
}
let [d, q] = unused_chars(text)
.ok_or_else(|| IoError::Format("the file holds every character, so its fields can't be read without a delimiter".into()))?;
Ok((delim.unwrap_or(d), quote.unwrap_or(q)))
}
/// Two characters `text` doesn't hold: noncharacters when it leaves two of them free, else the
/// first two free scalar values (a 136 KiB bitset, only for a text holding all 32 noncharacters).
fn unused_chars(text: &str) -> Option<[char; 2]> {
const FIRST: u32 = 0xFDD0;
let mut used = 0u32;
for c in text.chars() {
if let Some(i) = (c as u32).checked_sub(FIRST).filter(|&i| i < 32) {
used |= 1 << i;
}
}
let mut free = (0..32).filter(|i| used & (1 << i) == 0).filter_map(|i| char::from_u32(FIRST + i));
if let (Some(d), Some(q)) = (free.next(), free.next()) {
return Some([d, q]);
}
let mut all = vec![0u64; 0x11_0000 / 64];
for c in text.chars() {
if let Some(w) = all.get_mut(c as usize / 64) {
*w |= 1 << (c as u32 % 64);
}
}
let mut free = (0..0x11_0000u32).filter(|&u| all.get(u as usize / 64).is_some_and(|w| w & (1 << (u % 64)) == 0)).filter_map(char::from_u32);
Some([free.next()?, free.next()?])
}
/// How many rows and bytes of a text file are read to decide each column's date order.
const DATE_SAMPLE_ROWS: usize = 200;
const DATE_SAMPLE_BYTES: usize = 1 << 20;
@@ -254,16 +316,34 @@ pub fn read_csv(bytes: &[u8], opts: &CsvOptions) -> Result<Workbook, IoError> {
pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook, ReadReport), IoError> {
let text = decode_text(bytes);
let quote = if opts.quote == 0 { '"' } else { opts.quote as char };
let delim = if opts.delimiter == 0 { sniff_delimiter(&text, quote) } else { opts.delimiter } as char;
if delim == quote {
return Err(IoError::Format("the delimiter and quote character must differ".into()));
}
let date_columns = if opts.parse_values { infer_date_rules(&sample_records(&text, delim, quote), opts.date_system) } else { vec![] };
let mut report = ReadReport::default();
date_warnings(&date_columns, &mut report);
let mut wb = Workbook::new();
wb.date_system = opts.date_system;
wb.csv_delimiter = u8::try_from(delim).ok();
// A detected delimiter: a `sep=` line names it (and isn't data), else the text shows it.
let sep = if opts.delimiter == 0 { sep_line(&text, quote) } else { None };
let (body, delim, quote) = match sep {
Some((d, skip)) => {
// Saved again with it only when the text would be read with it again without the line
// (Excel saves with its list separator and drops the line); else with the CSV default,
// comma. `sep=;` over `a;b,c` keeps commas: detection would pick them.
let body = text.get(skip..).unwrap_or_default();
wb.csv_delimiter =
d.filter(|d| [',', ';', '\t'].contains(d) && sniff_delimiter(body, quote) as char == *d).and_then(|d| u8::try_from(d).ok());
// `sep="`: Excel splits at the quotes, so nothing is quoted.
(body, d, Some(quote).filter(|q| d != Some(*q)))
}
None => {
let delim = if opts.delimiter == 0 { sniff_delimiter(&text, quote) } else { opts.delimiter } as char;
if delim == quote {
return Err(IoError::Format("the delimiter and quote character must differ".into()));
}
wb.csv_delimiter = u8::try_from(delim).ok();
(text.as_str(), Some(delim), Some(quote))
}
};
let (delim, quote) = stand_ins(body, delim, quote)?;
let date_columns = if opts.parse_values { infer_date_rules(&sample_records(body, delim, quote), opts.date_system) } else { vec![] };
let mut report = ReadReport::default();
date_warnings(&date_columns, &mut report);
let mut sheet = Sheet::new("Sheet1");
let mut styles = std::mem::take(&mut wb.styles);
let mut fmt_cache: Vec<(&'static str, StyleId)> = vec![];
@@ -271,7 +351,7 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook
// The bounding box of the non-empty cells, which is the sheet's used range.
let mut used: Option<(u32, u32, u32, u32)> = None;
let mut too_many = false;
parse_records(&text, delim, quote, |rec| {
parse_records(body, delim, quote, |rec| {
if row >= MAX_ROWS {
return false;
}
@@ -339,7 +419,25 @@ pub fn write_csv(sheet: &Sheet, delimiter: u8, cell_text: impl FnMut(CellRef) ->
}
/// [`write_csv`] with the output cap `limit` (bytes) given.
pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, mut cell_text: impl FnMut(CellRef) -> String) -> Result<Vec<u8>, IoError> {
pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, cell_text: impl FnMut(CellRef) -> String) -> Result<Vec<u8>, IoError> {
write_delimited(sheet, delimiter, limit, true, cell_text)
}
/// The sheet as tab-separated text (`.tsv`, `.txt`), like [`write_csv`] with tabs. Such a file is
/// read with tabs given, never by detection, so a first cell like `sep=;` stays data without the
/// `sep=` line a CSV needs: that line would come back as an extra row.
pub fn write_tsv(sheet: &Sheet, cell_text: impl FnMut(CellRef) -> String) -> Result<Vec<u8>, IoError> {
write_delimited(sheet, b'\t', MAX_CSV_BYTES, false, cell_text)
}
/// [`write_csv_limited`], and with `sep_guard` a first row that reads as a `sep=` line gets one.
fn write_delimited(
sheet: &Sheet,
delimiter: u8,
limit: usize,
sep_guard: bool,
mut cell_text: impl FnMut(CellRef) -> String,
) -> Result<Vec<u8>, IoError> {
let delim = if delimiter == 0 { ',' } else { delimiter as char };
let mut out = String::new();
let Some(r) = sheet.used_range() else { return Ok(Vec::new()) };
@@ -371,5 +469,18 @@ pub fn write_csv_limited(sheet: &Sheet, delimiter: u8, limit: usize, mut cell_te
return Err(too_large(format!("more than {} MiB (stopped at row {})", limit >> 20, row + 1)));
}
}
// A `sep=` line naming the delimiter, which GridCraft and Excel both drop on opening, goes first
// when the file wouldn't reopen in the same columns without it: a first row that would read as
// Excel's `sep=` line (a lone `sep=;` cell) stays data, and output that detection would read
// with another delimiter (`a,b;x` once `"a,b"` lost its quotes) keeps its own.
let first_is_sep = out.split(['\r', '\n']).next().is_some_and(|first| sep_line(first, '"').is_some());
if sep_guard && (first_is_sep || sniff_delimiter(&out, '"') != delim as u8) {
let line = format!("sep={delim}\r\n");
// The line counts against the cap like the rows.
if out.len().saturating_add(line.len()) > limit {
return Err(too_large(format!("more than {} MiB with its sep= line", limit >> 20)));
}
out.insert_str(0, &line);
}
Ok(out.into_bytes())
}
+1 -1
View File
@@ -48,7 +48,7 @@ use gridcraft_core::DateSystem;
use gridcraft_model::Workbook;
pub use crypto::{DecryptError, check_encryption, decrypt};
pub use csv::{MAX_CSV_BYTES, decode_text, read_csv, read_csv_with_report, write_csv, write_csv_limited};
pub use csv::{MAX_CSV_BYTES, decode_text, read_csv, read_csv_with_report, write_csv, write_csv_limited, write_tsv};
pub use ods::read_ods;
pub use package::MAX_PART;
pub use passthrough::rebase_links;
+120
View File
@@ -418,6 +418,102 @@ fn parser_stops_collecting_fields_at_max_cols() {
assert_eq!(lens, vec![MAX_COLS as usize]);
}
/// #1446: a first line `sep=` plus one character names the delimiter and isn't data, as Excel 16.0
/// reads it when it opens a CSV file. Each case: file → first two rows.
#[test]
fn sep_line_names_the_delimiter() {
let read = |src: &str| -> Vec<String> {
let wb = read_csv(src.as_bytes(), &CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }).unwrap();
let sh = wb.sheet(0).unwrap();
let cell = |r, c| sh.value(CellRef::new(r, c)).as_text().map(|t| t.to_string()).unwrap_or_default();
(0..2).map(|r| (0..3).map(|c| cell(r, c)).collect::<Vec<_>>().join("|").trim_end_matches('|').to_string()).collect()
};
// Named delimiters, whatever the text would suggest.
assert_eq!(read("sep=|\r\nA|B\r\n1|2\r\n"), ["A|B", "1|2"]);
assert_eq!(read("sep=;\nA;B,C\n"), ["A|B,C", ""]);
assert_eq!(read("sep=,\r\n1,5;2\r\n"), ["1|5;2", ""]);
assert_eq!(read("sep=\t\r\nA\tB\r\n"), ["A|B", ""]);
assert_eq!(read("sep=x\r\nAxB\r\n"), ["A|B", ""]);
// Spaces anywhere, upper case, the line quoted as a field, a BOM before it.
for src in ["sep= |\r\nA|B", "sep =|\r\nA|B", " sep=| \r\nA|B", "SEP=|\r\nA|B", "\"sep=|\"\r\nA|B", "\u{feff}sep=|\r\nA|B"] {
assert_eq!(read(src), ["A|B", ""], "{src:?}");
}
// `sep=` naming nothing (or a space) is dropped and splits nothing.
assert_eq!(read("sep=\r\nA;B\tC,D\r\n"), ["A;B\tC,D", ""]);
assert_eq!(read("sep= \r\nA,B\r\n"), ["A,B", ""]);
assert_eq!(read("sep=|"), ["", ""], "only the line: an empty sheet");
// `sep="`: split at the quotes.
assert_eq!(read("sep=\"\r\nA\"B\r\n"), ["A|B", ""]);
// Data: two characters after `=` (a tab counts), the line anywhere but first, an unclosed quote.
assert_eq!(read("sep=ab\r\nAaB\r\n"), ["sep=ab", "AaB"]);
assert_eq!(read("sep=|\t\r\nA|B\r\n"), ["sep=|\t", "A|B"]);
assert!(read("sep=;,\r\nA;B,C\r\n")[0].starts_with("sep=;"), "data, split as the text suggests");
assert_eq!(read("A,B\r\nsep=,\r\n"), ["A|B", "sep="], "a data row, split at its comma");
// A delimiter that was given wins, and the line stays data.
let wb = read_csv(b"sep=|\r\nA|B\r\n", &CsvOptions { delimiter: b',', ..Default::default() }).unwrap();
assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(0, 0)), Value::text("sep=|"));
// Saved again with the named delimiter only when it would be detected without the line.
let delim = |src: &str| read_csv(src.as_bytes(), &CsvOptions { delimiter: 0, ..Default::default() }).unwrap().csv_delimiter;
assert_eq!(delim("sep=;\r\nA;B"), Some(b';'));
assert_eq!(delim("sep=\t\r\nA\tB"), Some(b'\t'));
assert_eq!(delim("sep=|\r\nA|B"), None, "| isn't detected: saved with commas so it reopens in columns");
}
/// Review of #2270: the delimiter a `sep=` line names is kept for saving only if the text would be
/// read with it again.
#[test]
fn a_named_delimiter_is_kept_only_if_it_would_be_detected_again() {
let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() };
let texts = |wb: &Workbook| -> Vec<String> {
let sh = wb.sheet(0).unwrap();
(0..2).flat_map(|r| (0..2).map(move |c| CellRef::new(r, c))).map(|c| sh.value(c).as_text().unwrap_or("").to_string()).collect()
};
let save = |wb: &Workbook| {
let sh = wb.sheet(0).unwrap();
write_csv(sh, wb.csv_delimiter.unwrap_or(b','), |c| sh.value(c).as_text().unwrap_or("").to_string()).unwrap()
};
// `;` named, but `a;b,c` would be detected as commas: saved with commas, it reopens the same.
let wb = read_csv(b"sep=;\na;b,c\n1;2,3\n", &opts).unwrap();
assert_eq!(texts(&wb), ["a", "b,c", "1", "2,3"]);
assert_eq!(wb.csv_delimiter, None);
let saved = save(&wb);
assert_eq!(saved, b"a,\"b,c\"\r\n1,\"2,3\"\r\n");
assert_eq!(texts(&read_csv(&saved, &opts).unwrap()), ["a", "b,c", "1", "2,3"]);
// `;` named and detected again: kept.
assert_eq!(read_csv(b"sep=;\na;b\n1;2\n", &opts).unwrap().csv_delimiter, Some(b';'));
}
#[test]
fn sep_line_counts_against_the_output_limit() {
let mut sheet = Sheet::new("Sheet1");
sheet.set_value(CellRef::new(0, 0), Value::text("sep=;"));
let text = |c: CellRef| sheet.value(c).as_text().unwrap_or("").to_string();
// The row is 7 bytes and fits; with the `sep=,` line it needs 14.
assert!(matches!(write_csv_limited(&sheet, b',', 7, text), Err(IoError::TooLarge(_))));
assert_eq!(write_csv_limited(&sheet, b',', 14, text).unwrap(), b"sep=,\r\nsep=;\r\n");
}
/// Review of #2270: a first row that looks like a `sep=` line (a lone `sep=;` in A1) is data. Saved
/// behind a `sep=,` line it opens as it was; Excel writes it bare and reads it back garbled.
#[test]
fn a_first_row_like_a_sep_line_survives_a_save() {
let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() };
let texts = |wb: &Workbook| -> Vec<String> {
let sh = wb.sheet(0).unwrap();
(0..2).flat_map(|r| (0..2).map(move |c| CellRef::new(r, c))).map(|c| sh.value(c).as_text().unwrap_or("").to_string()).collect()
};
let mut sheet = Sheet::new("Sheet1");
sheet.set_value(CellRef::new(0, 0), Value::text("sep=;"));
sheet.set_value(CellRef::new(1, 0), Value::text("value"));
let saved = write_csv(&sheet, b',', |c| sheet.value(c).as_text().unwrap_or("").to_string()).unwrap();
assert_eq!(saved, b"sep=,\r\nsep=;\r\nvalue\r\n");
assert_eq!(texts(&read_csv(&saved, &opts).unwrap()), ["sep=;", "", "value", ""]);
// Other first rows are written as before.
let mut plain = Sheet::new("Sheet1");
plain.set_value(CellRef::new(0, 0), Value::text("separator"));
assert_eq!(write_csv(&plain, b',', |c| plain.value(c).as_text().unwrap_or("").to_string()).unwrap(), b"separator\r\n");
}
#[test]
fn a_field_over_32767_characters_is_cut() {
let src = format!("{},{},'{}", "x".repeat(40_000), "y".repeat(32_768), "z".repeat(40_000));
@@ -445,3 +541,27 @@ fn csv_used_range_limit_is_enforced_while_reading() {
// No limit by default.
assert!(read_csv(dense, &CsvOptions::default()).is_ok());
}
/// `sep=` naming nothing reads through craft-csv with a stand-in delimiter the text doesn't hold
/// (`sep_line_names_the_delimiter` has the usual cases). A text holding every noncharacter still
/// opens whole: another character stands in. Review of #2270: it was split at U+FDD0.
#[test]
fn sep_line_stand_in_survives_a_text_holding_every_stand_in() {
let all: String = (0xFDD0..=0xFDEF).filter_map(char::from_u32).collect();
let text = format!("sep=\r\nx{all}y\r\n\0z\r\n");
let wb = read_csv(text.as_bytes(), &CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }).unwrap();
let sh = wb.sheet(0).unwrap();
assert_eq!(sh.value(CellRef::new(0, 0)), Value::text(format!("x{all}y")), "the whole line is one field");
assert_eq!(sh.value(CellRef::new(0, 1)), Value::Empty);
assert_eq!(sh.value(CellRef::new(1, 0)), Value::text("\0z"));
}
/// A text that holds every character leaves nothing to stand in for the missing delimiter: it's
/// refused, not split at one of its own characters.
#[test]
fn sep_line_without_a_free_stand_in_is_refused() {
let all: String = (0..=0x10_FFFF).filter_map(char::from_u32).filter(|c| !matches!(c, '\r' | '\n')).collect();
let text = format!("sep=\r\n{all}\r\n");
let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() };
assert!(matches!(read_csv(text.as_bytes(), &opts), Err(IoError::Format(_))));
}
+26
View File
@@ -159,3 +159,29 @@ errs on the wide side; a UI test checks that the real font then draws the number
Excel doesn't widen when a value is entered into a cell that already has the format (observed through
the `Value` property: the cell shows `####`), and neither does GridCraft. Typing into such a cell
wasn't observed.
## CSV: Excel's `sep=` first line (#1446)
A CSV file whose first line is `sep=` plus one character is split at that character when File ›
Open detects the delimiter, and the line isn't data. Observed in Excel 16.0 (build 17932, Windows)
opening synthetic files: spaces anywhere in the line are ignored (`sep= |`, ` sep=| `), case
doesn't matter, the line may be quoted as a whole field, and a BOM before it is fine. `sep=` with
nothing after it (or only spaces) is dropped and nothing is split; a non-ASCII character is dropped
the same way. Two characters after `=` (a tab counts, `sep=|<tab>`), or the line anywhere but first,
is data. `sep="` splits at the quotes, so nothing is quoted. (#1446 measured `sep=` alone as data in
Excel for Microsoft 365, de-DE; this build drops it.)
A delimiter given by the caller wins and the line stays data, so a `.tsv`/`.txt` file (read with
tabs) keeps it. Saving: Excel writes its list separator and drops the line. GridCraft saves a CSV
with the separator it was read with, so it keeps a named `,` `;` or tab only when detection picks
it again on reopening; otherwise (`|`, or `sep=;` over text with as many commas) it saves commas.
Saving drops quotes a field no longer needs, so the written text can still read differently
(`"a,b";x` saved with `;` is `a,b;x`, a tie that detection gives to comma; `a;b;c|d;e;f` saved with
commas is `a;b;c,d;e;f`, which detection reads as `;`). Whenever detection on the written text would
pick another delimiter, or a first row would itself read as a `sep=` line (a lone `sep=;` cell), the
file starts with a `sep=` line naming its delimiter, so it reopens in the same columns. A `.tsv` or
`.txt` file is read with tabs given, so it gets no such line. Excel writes
such a row bare (`"sep=;";`) and reopens the file garbled (observed: A1 `sep=;;`, row 2 in one cell).
From Text/CSV still guesses its own delimiter; making it detect like File › Open (and so honour
`sep=`) is another part of #1446.
File diff suppressed because one or more lines are too long