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

updates #11

Merged
merged 2 commits into from
Feb 27, 2024
Merged
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ Cargo.lock
*.bk
.vim
fuzz.xlsx
.idea
.idea
nyc.rs
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rust-analyzer.showUnlinkedFileNotification": false
}
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "calamine"
version = "0.22.1"
version = "0.24.0"
authors = ["Johann Tuffe <[email protected]>"]
repository = "https://github.com/tafia/calamine"
documentation = "https://docs.rs/calamine"
Expand All @@ -11,7 +11,7 @@ keywords = ["excel", "ods", "xls", "xlsx", "xlsb"]
categories = ["encoding", "parsing", "text-processing"]
exclude = ["tests/**/*"]
edition = "2021"
rust-version = "1.63"
rust-version = "1.65"

[dependencies]
byteorder = "1.4"
Expand All @@ -20,7 +20,7 @@ encoding_rs = "0.8"
log = "0.4"
once_cell = { version = "1.18", optional = true }
serde = "1.0"
quick-xml = { version = "0.30", features = ["encoding"] }
quick-xml = { version = "0.31", features = ["encoding"] }
zip = { version = "0.6", default-features = false, features = ["deflate"] }
chrono = { version = "0.4", features = [
"serde",
Expand Down
24 changes: 23 additions & 1 deletion Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,28 @@

## Unreleased

## 0.24.0

- refactor (breaking): rename `DataType` enum to `Data` and `DataTypeRef` to `DataRef`
- feat: introduce a `DataType` trait implemented by both `Data` and `DataRef`.
- feat: `Data` and `DataType` now return `Some(0{.0})` and `Some(1{.0})` rather than `None` when `.as_i64` or `.as_f64`
is used on a Bool value
- fix: getting tables names on xlsx workbook without _rels files
- refactor: DateTime(f64) to DateTime(ExcelDateTime)
- feat: detect xlsb/ods password protected files
- feat: introduce is_x methods for date and time variants

## 0.23.1

- fix: `worksheet_formula` not returning all formula

## 0.23.0

- feat: add new `DataTypeRef` available from `worksheet_range_ref` to reduce memory usage
- docs: add benchmark plot
- fix: truncated text in xls
- feat: detect if workbook is password protected

## 0.22.1

- fix: regression on `Range::get`
Expand Down Expand Up @@ -135,7 +157,7 @@
- fix: xls - allow sectors ending after eof (truncate them!)

## 0.15.0
- feat: codepage/encoding_rs for codpage mapping
- feat: codepage/encoding_rs for codpage mapping

## 0.14.10
- fix: serde map do not stop at first empty value
Expand Down
36 changes: 26 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ An Excel/OpenDocument Spreadsheets file reader/deserializer, in pure Rust.
## Description

**calamine** is a pure Rust library to read and deserialize any spreadsheet file:

- excel like (`xls`, `xlsx`, `xlsm`, `xlsb`, `xla`, `xlam`)
- opendocument spreadsheets (`ods`)

Expand Down Expand Up @@ -47,25 +48,23 @@ fn example() -> Result<(), Error> {
Note if you want to deserialize a column that may have invalid types (i.e. a float where some values may be strings), you can use Serde's `deserialize_with` field attribute:

```rust
use serde::Deserialize;
use serde::{DataType, Deserialize};
use calamine::{RangeDeserializerBuilder, Reader, Xlsx};


#[derive(Deserialize)]
struct ExcelRow {
struct Record {
metric: String,
#[serde(deserialize_with = "de_opt_f64")]
value: Option<f64>,
}


// Convert value cell to Some(f64) if float or int, else None
fn de_opt_f64<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
where
D: serde::Deserializer<'de>,
{
let data_type = calamine::DataType::deserialize(deserializer)?;
if let Some(float) = data_type.as_f64() {
let data = calamine::Data::deserialize(deserializer)?;
if let Some(float) = data.as_f64() {
Ok(Some(float))
} else {
Ok(None)
Expand All @@ -81,10 +80,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.ok_or(calamine::Error::Msg("Cannot find Sheet1"))??;

let iter_result =
RangeDeserializerBuilder::with_headers(&COLUMNS).from_range::<_, ExcelRow>(&range)?;
}
```
RangeDeserializerBuilder::with_headers(&["metric", "value"]).from_range(&range)?;

for result in iter_results {
let record: Record = result?;
println!("metric={:?}, value={:?}", record.metric, record.value);
}
}
```

### Reader: Simple

Expand All @@ -102,6 +105,7 @@ if let Some(Ok(r)) = excel.worksheet_range("Sheet1") {
### Reader: More complex

Let's assume

- the file type (xls, xlsx ...) cannot be known at static time
- we need to get all data from the workbook
- we need to parse the vba
Expand Down Expand Up @@ -160,7 +164,7 @@ for s in sheets {

## Features

- `dates`: Add date related fn to `DataType`.
- `dates`: Add date related fn to `DataType`.
- `picture`: Extract picture data.

### Others
Expand All @@ -170,6 +174,7 @@ Browse the [examples](https://github.com/tafia/calamine/tree/master/examples) di
## Performance

As `calamine` is readonly, the comparisons will only involve reading an excel `xlsx` file and then iterating over the rows. Along with `calamine`, three other libraries were chosen, from three different languages:

- [`excelize`](https://github.com/qax-os/excelize) written in `go`
- [`ClosedXML`](https://github.com/ClosedXML/ClosedXML) written in `C#`
- [`openpyxl`](https://foss.heptapod.net/openpyxl/openpyxl) written in `python`
Expand All @@ -179,6 +184,7 @@ The benchmarks were done using this [dataset](https://raw.githubusercontent.com/
The programs are all structured to follow the same constructs:

`calamine`:

```rust
use calamine::{open_workbook, Reader, Xlsx};

Expand All @@ -199,6 +205,7 @@ fn main() {
```

`excelize`:

```go
package main

Expand Down Expand Up @@ -237,6 +244,7 @@ func main() {
```

`ClosedXML`:

```csharp
using ClosedXML.Excel;

Expand All @@ -261,6 +269,7 @@ internal class Program
```

`openpyxl`:

```python
from openpyxl import load_workbook

Expand Down Expand Up @@ -306,6 +315,7 @@ v2.8.0 excelize.exe
The spreadsheet has a range of 1,000,001 rows and 41 columns, for a total of 41,000,041 cells in the range. Of those, 28,056,975 cells had values.

Going off of that number:

- `calamine` => 1,122,279 cells per second
- `excelize` => 633,998 cells per second
- `ClosedXML` => 157,320 cells per second
Expand All @@ -314,9 +324,11 @@ Going off of that number:
### Plots

#### Disk Read

![bytes_from_disk](https://github.com/RoloEdits/calamine/assets/12489689/fcca1147-d73f-4d1c-b273-e7e4c183ab29)

As stated, the filesize on disk is `186MB`:

- `calamine` => `186MB`
- `ClosedXML` => `208MB`.
- `openpyxl` => `192MB`.
Expand All @@ -328,11 +340,13 @@ When asking one of the maintainers of `excelize`, I got this [response](https://
> \- xuri

#### Disk Write

![bytes_to_disk](https://github.com/RoloEdits/calamine/assets/12489689/befa9893-7658-41a7-8cbd-b0ce5a7d9341)

As seen in the previous section, `excelize` is writting to disk to save memory. The others don't employ that kind of mechanism.

#### Memory

![mem_usage](https://github.com/RoloEdits/calamine/assets/12489689/c83fdf6b-1442-4e22-8eca-84cbc1db4a26)

![virt_mem_usage](https://github.com/RoloEdits/calamine/assets/12489689/840a96ed-33d7-44f7-8276-80bb7a02557f)
Expand All @@ -342,6 +356,7 @@ As seen in the previous section, `excelize` is writting to disk to save memory.
The stepping and falling for `calamine` is from the grows of `Vec`s and the freeing of memory right after, with the memory usage dropping down again. The sudden jump at the end is when the sheet is being read into memory. The others, being garbage collected, have a more linear climb all the way through.

#### CPU

![cpu_usage](https://github.com/RoloEdits/calamine/assets/12489689/c3aa55a8-b008-48ee-ba04-c08bd91c1f6f)

Very noisy chart, but `excelize`'s spikes must be from the GC?
Expand All @@ -351,6 +366,7 @@ Very noisy chart, but `excelize`'s spikes must be from the GC?
Many (most) part of the specifications are not implemented, the focus has been put on reading cell **values** and **vba** code.

The main unsupported items are:

- no support for writing excel files, this is a read-only library
- no support for reading extra contents, such as formatting, excel parameter, encrypted components etc ...
- no support for reading VB for opendocuments
Expand Down
39 changes: 38 additions & 1 deletion benches/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ fn count<R: Reader<BufReader<File>>>(path: &str) -> usize {
count += excel
.worksheet_range(&s)
.unwrap()
.unwrap()
.rows()
.flat_map(|r| r.iter())
.count();
Expand All @@ -44,3 +43,41 @@ fn bench_xlsb(b: &mut Bencher) {
fn bench_ods(b: &mut Bencher) {
b.iter(|| count::<Ods<_>>("tests/issues.ods"));
}

#[bench]
fn bench_xlsx_cells_reader(b: &mut Bencher) {
fn count<R: Reader<BufReader<File>>>(path: &str) -> usize {
let path = format!("{}/{}", env!("CARGO_MANIFEST_DIR"), path);
let mut excel: Xlsx<_> = open_workbook(&path).expect("cannot open excel file");

let sheets = excel.sheet_names().to_owned();
let mut count = 0;
for s in sheets {
let mut cells_reader = excel.worksheet_cells_reader(&s).unwrap();
while let Some(_) = cells_reader.next_cell().unwrap() {
count += 1;
}
}
count
}
b.iter(|| count::<Xlsx<_>>("tests/issues.xlsx"));
}

#[bench]
fn bench_xlsb_cells_reader(b: &mut Bencher) {
fn count<R: Reader<BufReader<File>>>(path: &str) -> usize {
let path = format!("{}/{}", env!("CARGO_MANIFEST_DIR"), path);
let mut excel: Xlsb<_> = open_workbook(&path).expect("cannot open excel file");

let sheets = excel.sheet_names().to_owned();
let mut count = 0;
for s in sheets {
let mut cells_reader = excel.worksheet_cells_reader(&s).unwrap();
while let Some(_) = cells_reader.next_cell().unwrap() {
count += 1;
}
}
count
}
b.iter(|| count::<Xlsx<_>>("tests/issues.xlsb"));
}
23 changes: 11 additions & 12 deletions examples/excel_to_csv.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use calamine::{open_workbook_auto, DataType, Range, Reader};
use calamine::{open_workbook_auto, Data, Range, Reader};
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
Expand All @@ -24,26 +24,25 @@ 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().unwrap();
let range = xl.worksheet_range(&sheet).unwrap();

write_range(&mut dest, &range).unwrap();
}

fn write_range<W: Write>(dest: &mut W, range: &Range<DataType>) -> std::io::Result<()> {
fn write_range<W: Write>(dest: &mut W, range: &Range<Data>) -> std::io::Result<()> {
let n = range.get_size().1 - 1;
for r in range.rows() {
for (i, c) in r.iter().enumerate() {
match *c {
DataType::Empty => Ok(()),
DataType::String(ref s)
| DataType::DateTimeIso(ref s)
| DataType::DurationIso(ref s) => write!(dest, "{}", s),
DataType::Float(ref f) | DataType::DateTime(ref f) | DataType::Duration(ref f) => {
write!(dest, "{}", f)
Data::Empty => Ok(()),
Data::String(ref s) | Data::DateTimeIso(ref s) | Data::DurationIso(ref s) => {
write!(dest, "{}", s)
}
DataType::Int(ref i) => write!(dest, "{}", i),
DataType::Error(ref e) => write!(dest, "{:?}", e),
DataType::Bool(ref b) => write!(dest, "{}", b),
Data::Float(ref f) => write!(dest, "{}", f),
Data::DateTime(ref d) => write!(dest, "{}", d.as_f64()),
Data::Int(ref i) => write!(dest, "{}", i),
Data::Error(ref e) => write!(dest, "{:?}", e),
Data::Bool(ref b) => write!(dest, "{}", b),
}?;
if i != n {
write!(dest, ";")?;
Expand Down
9 changes: 3 additions & 6 deletions examples/search_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;

use calamine::{open_workbook_auto, DataType, Error, Reader};
use calamine::{open_workbook_auto, Data, Error, Reader};
use glob::{glob, GlobError, GlobResult};

#[derive(Debug)]
Expand Down Expand Up @@ -74,15 +74,12 @@ fn run(f: GlobResult) -> Result<(PathBuf, Option<usize>, usize), FileStatus> {
let sheets = xl.sheet_names().to_owned();

for s in sheets {
let range = xl
.worksheet_range(&s)
.unwrap()
.map_err(FileStatus::RangeError)?;
let range = xl.worksheet_range(&s).map_err(FileStatus::RangeError)?;
cell_errors += range
.rows()
.flat_map(|r| {
r.iter().filter(|c| {
if let DataType::Error(_) = **c {
if let Data::Error(_) = **c {
true
} else {
false
Expand Down
Loading