Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: check for memory errors on reading xlsx files and proper formatting of csv sample code #432

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions examples/excel_to_csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,13 @@ fn main() {
let dest = sce.with_extension("csv");
let mut dest = BufWriter::new(File::create(dest).unwrap());
let mut xl = open_workbook_auto(&sce).unwrap();
let range = xl.worksheet_range(&sheet).unwrap();

write_range(&mut dest, &range).unwrap();
let range = xl.worksheet_range(&sheet);
if range.is_err() {
/// Capture error however you want
std::process::exit(1);
} else {
write_range(&mut dest, &range.unwrap()).unwrap();
}
}

fn write_range<W: Write>(dest: &mut W, range: &Range<Data>) -> std::io::Result<()> {
Expand All @@ -36,7 +40,7 @@ fn write_range<W: Write>(dest: &mut W, range: &Range<Data>) -> std::io::Result<(
match *c {
Data::Empty => Ok(()),
Data::String(ref s) | Data::DateTimeIso(ref s) | Data::DurationIso(ref s) => {
write!(dest, "{}", s)
write!(dest, "\"{}\"", s.replace("\"", "\"\""))
}
Data::Float(ref f) => write!(dest, "{}", f),
Data::DateTime(ref d) => write!(dest, "{}", d.as_f64()),
Expand All @@ -45,7 +49,7 @@ fn write_range<W: Write>(dest: &mut W, range: &Range<Data>) -> std::io::Result<(
Data::Bool(ref b) => write!(dest, "{}", b),
}?;
if i != n {
write!(dest, ";")?;
write!(dest, ",")?;
}
}
write!(dest, "\r\n")?;
Expand Down
8 changes: 8 additions & 0 deletions src/xlsx/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,7 @@ impl<RS: Read + Seek> Xlsx<RS> {
) -> Result<Range<DataRef<'a>>, XlsxError> {
let mut cell_reader = self.worksheet_cells_reader(name)?;
let len = cell_reader.dimensions().len();
let usize_len: usize = len as usize;
let mut cells = Vec::new();
if len < 100_000 {
cells.reserve(len as usize);
Expand All @@ -823,6 +824,13 @@ impl<RS: Read + Seek> Xlsx<RS> {
Err(e) => return Err(e),
}
}
/// Chcek for machine memory error
if cells.capacity() < usize_len {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo

match cells.try_reserve(len as usize - cells.capacity()) {
Ok(_) => (),
Err(e) => return Err(XlsxError::CellError(e.to_string())),
}
}
Ok(Range::from_sparse(cells))
}
}
Expand Down