python-calamine 0.9.1__tar.gz → 0.10.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {python_calamine-0.9.1 → python_calamine-0.10.0}/.github/workflows/CI.yml +44 -18
  2. {python_calamine-0.9.1 → python_calamine-0.10.0}/Cargo.lock +3 -3
  3. {python_calamine-0.9.1 → python_calamine-0.10.0}/Cargo.toml +2 -2
  4. {python_calamine-0.9.1 → python_calamine-0.10.0}/PKG-INFO +16 -1
  5. {python_calamine-0.9.1 → python_calamine-0.10.0}/README.md +15 -0
  6. {python_calamine-0.9.1 → python_calamine-0.10.0}/python/python_calamine/__init__.py +2 -0
  7. {python_calamine-0.9.1 → python_calamine-0.10.0}/python/python_calamine/_python_calamine.pyi +63 -0
  8. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/lib.rs +2 -1
  9. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/mod.rs +2 -0
  10. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/workbook.rs +17 -1
  11. python_calamine-0.10.0/src/types/workbook_properties.rs +140 -0
  12. python_calamine-0.10.0/tests/data/workbook_properties.ods +0 -0
  13. python_calamine-0.10.0/tests/data/workbook_properties.xlsx +0 -0
  14. python_calamine-0.10.0/tests/test_workbook_properties.py +156 -0
  15. {python_calamine-0.9.1 → python_calamine-0.10.0}/.github/dependabot.yml +0 -0
  16. {python_calamine-0.9.1 → python_calamine-0.10.0}/.github/pyodide/pylock.314.toml +0 -0
  17. {python_calamine-0.9.1 → python_calamine-0.10.0}/.github/pyodide/pylock.315.toml +0 -0
  18. {python_calamine-0.9.1 → python_calamine-0.10.0}/.github/pyodide/requirements.in +0 -0
  19. {python_calamine-0.9.1 → python_calamine-0.10.0}/.gitignore +0 -0
  20. {python_calamine-0.9.1 → python_calamine-0.10.0}/.pre-commit-config.yaml +0 -0
  21. {python_calamine-0.9.1 → python_calamine-0.10.0}/LICENSE +0 -0
  22. {python_calamine-0.9.1 → python_calamine-0.10.0}/build.rs +0 -0
  23. {python_calamine-0.9.1 → python_calamine-0.10.0}/pyproject.toml +0 -0
  24. {python_calamine-0.9.1 → python_calamine-0.10.0}/python/python_calamine/py.typed +0 -0
  25. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/cell.rs +0 -0
  26. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/errors.rs +0 -0
  27. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/sheet.rs +0 -0
  28. {python_calamine-0.9.1 → python_calamine-0.10.0}/src/types/table.rs +0 -0
  29. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/__init__.py +0 -0
  30. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/conftest.py +0 -0
  31. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/any_sheets.ods +0 -0
  32. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/any_sheets.xls +0 -0
  33. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/any_sheets.xlsb +0 -0
  34. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/any_sheets.xlsx +0 -0
  35. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/base.ods +0 -0
  36. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/base.xls +0 -0
  37. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/base.xlsb +0 -0
  38. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/base.xlsx +0 -0
  39. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/empty_file.ods +0 -0
  40. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/empty_file.xlsb +0 -0
  41. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/empty_file.xlsx +0 -0
  42. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/issue139.xlsx +0 -0
  43. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/password.ods +0 -0
  44. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/password.xls +0 -0
  45. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/password.xlsb +0 -0
  46. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/password.xlsx +0 -0
  47. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/data/table-multiple.xlsx +0 -0
  48. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/test_base.py +0 -0
  49. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/test_pandas.py +0 -0
  50. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/test_sheet_type.py +0 -0
  51. {python_calamine-0.9.1 → python_calamine-0.10.0}/tests/test_tables.py +0 -0
  52. {python_calamine-0.9.1 → python_calamine-0.10.0}/uv.lock +0 -0
@@ -119,7 +119,7 @@ jobs:
119
119
  persist-credentials: false
120
120
 
121
121
  - name: install uv
122
- uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
122
+ uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
123
123
  with:
124
124
  python-version: ${{ matrix.python-version }}
125
125
  enable-cache: true # zizmor: ignore[cache-poisoning] -- Job does not produce release artifacts and does not have sensitive permissions
@@ -192,7 +192,7 @@ jobs:
192
192
  jobs: ${{ toJSON(needs) }}
193
193
 
194
194
  build:
195
- name: build on ${{ matrix.os }} (${{ matrix.target }} - ${{ matrix.interpreter || 'all' }}${{ matrix.os == 'linux' && format(' - {0}', matrix.manylinux == 'auto' && 'manylinux' || matrix.manylinux) || '' }})
195
+ name: build on ${{ matrix.os }} (${{ matrix.arch }} - ${{ matrix.interpreter || 'all' }}${{ matrix.os == 'linux' && format(' - {0}', matrix.manylinux == 'auto' && 'manylinux' || matrix.manylinux) || '' }})
196
196
  permissions:
197
197
  contents: read
198
198
  if: success()
@@ -201,63 +201,89 @@ jobs:
201
201
  matrix:
202
202
  os: [linux, macos, windows]
203
203
  target: [undefined]
204
+ arch: [undefined]
204
205
  manylinux: [auto]
205
206
  include:
206
207
  # manylinux for various platforms
207
208
  - os: linux
208
209
  manylinux: auto
209
- target: x86_64
210
+ target: x86_64-unknown-linux-gnu
211
+ arch: x86_64
210
212
  - os: linux
211
213
  manylinux: auto
212
- target: aarch64
214
+ target: aarch64-unknown-linux-gnu
215
+ arch: aarch64
213
216
  - os: linux
214
217
  manylinux: auto
215
- target: i686
218
+ target: i686-unknown-linux-gnu
219
+ arch: x86
220
+ # https://github.com/PyO3/maturin-action/issues/484
221
+ runs-on: ubuntu-24.04
216
222
  - os: linux
217
223
  manylinux: auto
218
- target: armv7
224
+ target: armv7-unknown-linux-gnueabihf
225
+ arch: armv7
219
226
  interpreter: 3.11 3.12 3.13 3.14 3.14t 3.15 3.15t
220
227
  - os: linux
221
228
  manylinux: auto
222
- target: ppc64le
229
+ target: powerpc64le-unknown-linux-gnu
230
+ arch: ppc64le
223
231
  interpreter: 3.11 3.12 3.13 3.14 3.14t 3.15 3.15t
224
232
  - os: linux
225
233
  manylinux: auto
226
- target: s390x
234
+ target: s390x-unknown-linux-gnu
235
+ arch: s390x
227
236
  interpreter: 3.11 3.12 3.13 3.14 3.14t 3.15 3.15t
237
+ - os: linux
238
+ manylinux: auto
239
+ target: riscv64gc-unknown-linux-gnu
240
+ arch: riscv64
228
241
 
229
242
  # musllinux
230
243
  - os: linux
231
- manylinux: musllinux_1_1
232
- target: x86_64
244
+ manylinux: musllinux_1_2
245
+ target: x86_64-unknown-linux-musl
246
+ arch: x86_64
233
247
  - os: linux
234
- manylinux: musllinux_1_1
235
- target: aarch64
248
+ manylinux: musllinux_1_2
249
+ target: aarch64-unknown-linux-musl
250
+ arch: aarch64
251
+ - os: linux
252
+ manylinux: musllinux_1_2
253
+ target: armv7-unknown-linux-musleabihf
254
+ arch: armv7
236
255
  - os: linux
237
- manylinux: musllinux_1_1
238
- target: armv7
256
+ manylinux: musllinux_1_2
257
+ target: riscv64gc-unknown-linux-musl
258
+ arch: riscv64
239
259
 
240
260
  # macos
241
261
  - os: macos
242
262
  target: x86_64
263
+ arch: x86_64
243
264
  - os: macos
244
265
  target: aarch64
266
+ arch: aarch64
245
267
 
246
268
  # windows
247
269
  - os: windows
248
270
  target: x86_64
271
+ arch: x86_64
249
272
  interpreter: 3.11 3.12 3.13 3.14 3.14t 3.15 3.15t
250
273
  - os: windows
251
274
  target: i686
275
+ arch: x86
252
276
  interpreter: 3.11 3.12 3.13 3.14 3.15
253
277
  - os: windows
254
278
  target: aarch64
279
+ arch: aarch64
255
280
  runs-on: windows-11-arm
256
281
  interpreter: 3.11 3.12 3.13 3.14 3.14t
257
282
 
258
283
  exclude:
259
284
  # was just a dummy variable to set a default value for target
260
285
  - target: undefined
286
+ - arch: undefined
261
287
 
262
288
  runs-on: ${{ matrix.runs-on || format('{0}-latest', (matrix.os == 'linux' && 'ubuntu') || matrix.os) }}
263
289
  steps:
@@ -276,7 +302,7 @@ jobs:
276
302
  - run: pip install -U twine
277
303
 
278
304
  - name: build sdist
279
- if: ${{ matrix.os == 'linux' && matrix.target == 'x86_64' && matrix.manylinux == 'auto' }}
305
+ if: ${{ matrix.os == 'linux' && matrix.arch == 'x86_64' && matrix.manylinux == 'auto' }}
280
306
  uses: PyO3/maturin-action@e83996d129638aa358a18fbd1dfb82f0b0fb5d3b # v1.51.0
281
307
  with:
282
308
  command: sdist
@@ -297,7 +323,7 @@ jobs:
297
323
 
298
324
  - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
299
325
  with:
300
- name: python_calamine_pypi_files_${{ matrix.os }}_${{ matrix.target }}_${{ matrix.manylinux || 'auto' }}
326
+ name: python_calamine_pypi_files_${{ matrix.os }}_${{ matrix.arch }}_${{ matrix.manylinux || 'auto' }}
301
327
  path: dist
302
328
 
303
329
  build-pyemscripten:
@@ -314,7 +340,7 @@ jobs:
314
340
  with:
315
341
  persist-credentials: false
316
342
 
317
- - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
343
+ - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
318
344
  with:
319
345
  python-version: ${{ matrix.python-version }}
320
346
  enable-cache: ${{ !startsWith(github.ref, 'refs/tags/') }} # zizmor: ignore[cache-poisoning]
@@ -401,7 +427,7 @@ jobs:
401
427
  merge-multiple: true
402
428
 
403
429
  - name: Upload to GitHub
404
- uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
430
+ uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
405
431
  with:
406
432
  generate_release_notes: true
407
433
  files: |
@@ -47,9 +47,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
47
47
 
48
48
  [[package]]
49
49
  name = "calamine"
50
- version = "0.37.0"
50
+ version = "0.38.0"
51
51
  source = "registry+https://github.com/rust-lang/crates.io-index"
52
- checksum = "c9ca341b94bc4b29e08970b1a03914fad2dfe177e2ecb67fcd6de9046004aafb"
52
+ checksum = "f431b67cba6122a1f7d26b7adafc71bbdf07026095fe811f5efc025d8748e1d8"
53
53
  dependencies = [
54
54
  "atoi_simd",
55
55
  "byteorder",
@@ -411,7 +411,7 @@ dependencies = [
411
411
 
412
412
  [[package]]
413
413
  name = "python-calamine"
414
- version = "0.9.1"
414
+ version = "0.10.0"
415
415
  dependencies = [
416
416
  "calamine",
417
417
  "chrono",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "python-calamine"
3
- version = "0.9.1"
3
+ version = "0.10.0"
4
4
  edition = "2021"
5
5
  readme = "README.md"
6
6
 
@@ -9,7 +9,7 @@ name = "python_calamine"
9
9
  crate-type = ["cdylib"]
10
10
 
11
11
  [dependencies]
12
- calamine = { version = "0.37.0", features = ["chrono"] }
12
+ calamine = { version = "0.38.0", features = ["chrono"] }
13
13
  pyo3 = { version = "0.30.1", features = ["chrono"] }
14
14
  chrono = { version = "0.4.42", features = ["serde"] }
15
15
  pyo3-file = "0.18.0"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-calamine
3
- Version: 0.9.1
3
+ Version: 0.10.0
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Programming Language :: Python :: 3.11
@@ -69,6 +69,21 @@ workbook = CalamineWorkbook.from_path("file.xlsx").get_sheet_by_name("Sheet1").t
69
69
  # ]
70
70
  ```
71
71
 
72
+ Workbook document properties, such as the author, are available for xlsx, xlsb, xls and ods files.
73
+ ```python
74
+ from python_calamine import CalamineWorkbook
75
+
76
+ properties = CalamineWorkbook.from_path("file.xlsx").workbook_properties
77
+ properties.creator
78
+ # "John"
79
+ properties.last_modified_by
80
+ # "Jane"
81
+ properties.modified
82
+ # datetime.datetime(2024, 6, 20, 14, 22, tzinfo=datetime.timezone.utc)
83
+ properties.custom_properties
84
+ # {"Department": "Finance"}
85
+ ```
86
+
72
87
  Pandas 2.2 and above have built-in support of python-calamine.
73
88
 
74
89
  Also, you can find additional examples in [tests](https://github.com/dimastbk/python-calamine/blob/master/tests/test_base.py).
@@ -50,6 +50,21 @@ workbook = CalamineWorkbook.from_path("file.xlsx").get_sheet_by_name("Sheet1").t
50
50
  # ]
51
51
  ```
52
52
 
53
+ Workbook document properties, such as the author, are available for xlsx, xlsb, xls and ods files.
54
+ ```python
55
+ from python_calamine import CalamineWorkbook
56
+
57
+ properties = CalamineWorkbook.from_path("file.xlsx").workbook_properties
58
+ properties.creator
59
+ # "John"
60
+ properties.last_modified_by
61
+ # "Jane"
62
+ properties.modified
63
+ # datetime.datetime(2024, 6, 20, 14, 22, tzinfo=datetime.timezone.utc)
64
+ properties.custom_properties
65
+ # {"Department": "Finance"}
66
+ ```
67
+
53
68
  Pandas 2.2 and above have built-in support of python-calamine.
54
69
 
55
70
  Also, you can find additional examples in [tests](https://github.com/dimastbk/python-calamine/blob/master/tests/test_base.py).
@@ -11,6 +11,7 @@ from ._python_calamine import (
11
11
  TablesNotLoaded,
12
12
  TablesNotSupported,
13
13
  WorkbookClosed,
14
+ WorkbookProperties,
14
15
  WorksheetNotFound,
15
16
  XmlError,
16
17
  ZipError,
@@ -30,6 +31,7 @@ __all__ = (
30
31
  "TablesNotLoaded",
31
32
  "TablesNotSupported",
32
33
  "WorkbookClosed",
34
+ "WorkbookProperties",
33
35
  "WorksheetNotFound",
34
36
  "XmlError",
35
37
  "ZipError",
@@ -174,6 +174,57 @@ class CalamineTable:
174
174
  ]:
175
175
  """Returning data from table as list of lists."""
176
176
 
177
+ @typing.final
178
+ class WorkbookProperties:
179
+ """Document properties of a workbook.
180
+
181
+ Fields that the file doesn't store are `None`. `created` and `modified` are
182
+ timezone-aware when the file stores a UTC offset (xlsx, xlsb and xls always do)
183
+ and naive otherwise, for example in ods files saved by LibreOffice. A date the
184
+ file stores in another format is `None`.
185
+ """
186
+
187
+ creator: str | None
188
+ """Creator (author) of the workbook."""
189
+ last_modified_by: str | None
190
+ """User who last saved the workbook."""
191
+ created: datetime.datetime | None
192
+ """Creation date."""
193
+ modified: datetime.datetime | None
194
+ """Last modification date."""
195
+ title: str | None
196
+ """Title."""
197
+ subject: str | None
198
+ """Subject."""
199
+ description: str | None
200
+ """Description or comments."""
201
+ keywords: str | None
202
+ """Keywords."""
203
+ category: str | None
204
+ """Category."""
205
+ content_status: str | None
206
+ """Content status."""
207
+ revision: str | None
208
+ """Revision number."""
209
+ version: str | None
210
+ """Version."""
211
+ application: str | None
212
+ """Name of the application that created the workbook."""
213
+ app_version: str | None
214
+ """Version of the application that created the workbook."""
215
+ company: str | None
216
+ """Company."""
217
+ template: str | None
218
+ """Template the workbook is based on."""
219
+ manager: str | None
220
+ """Manager."""
221
+ custom_properties: dict[str, str]
222
+ """Custom document properties, keyed by name.
223
+
224
+ Values are returned as the text stored in the file, for example `"4"`,
225
+ `"true"` or `"2020-08-24T20:19:22Z"`.
226
+ """
227
+
177
228
  @typing.final
178
229
  class CalamineWorkbook:
179
230
  path: str | None
@@ -184,6 +235,17 @@ class CalamineWorkbook:
184
235
  """All sheets metadata of this workbook, in workbook order."""
185
236
  table_names: list[str] | None
186
237
  """All table names of this workbook."""
238
+ @property
239
+ def workbook_properties(self) -> WorkbookProperties:
240
+ """Document properties of this workbook, such as the creator and title.
241
+
242
+ Supported for xlsx, xlsb, xls and ods. The properties are read when this
243
+ attribute is first accessed, not when the workbook is opened.
244
+
245
+ Raises:
246
+ WorkbookClosed: If workbook already closed.
247
+ """
248
+
187
249
  @classmethod
188
250
  def from_object(
189
251
  cls, path_or_filelike: str | os.PathLike | ReadBuffer, load_tables: bool = False
@@ -309,6 +371,7 @@ __all__ = [
309
371
  "TablesNotLoaded",
310
372
  "TablesNotSupported",
311
373
  "WorkbookClosed",
374
+ "WorkbookProperties",
312
375
  "WorksheetNotFound",
313
376
  "XmlError",
314
377
  "ZipError",
@@ -4,7 +4,7 @@ mod types;
4
4
  use crate::types::{
5
5
  CalamineError, CalamineSheet, CalamineTable, CalamineWorkbook, CellValue, Error, PasswordError,
6
6
  SheetMetadata, SheetTypeEnum, SheetVisibleEnum, TableNotFound, TablesNotLoaded,
7
- TablesNotSupported, WorkbookClosed, WorksheetNotFound, XmlError, ZipError,
7
+ TablesNotSupported, WorkbookClosed, WorkbookProperties, WorksheetNotFound, XmlError, ZipError,
8
8
  };
9
9
 
10
10
  #[pyfunction]
@@ -26,6 +26,7 @@ fn _python_calamine(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
26
26
  m.add_class::<SheetTypeEnum>()?;
27
27
  m.add_class::<SheetVisibleEnum>()?;
28
28
  m.add_class::<CalamineTable>()?;
29
+ m.add_class::<WorkbookProperties>()?;
29
30
  m.add("CalamineError", py.get_type::<CalamineError>())?;
30
31
  m.add("PasswordError", py.get_type::<PasswordError>())?;
31
32
  m.add("WorksheetNotFound", py.get_type::<WorksheetNotFound>())?;
@@ -3,6 +3,7 @@ mod errors;
3
3
  mod sheet;
4
4
  mod table;
5
5
  mod workbook;
6
+ mod workbook_properties;
6
7
  pub use cell::CellValue;
7
8
  pub use errors::{
8
9
  CalamineError, Error, PasswordError, TableNotFound, TablesNotLoaded, TablesNotSupported,
@@ -11,3 +12,4 @@ pub use errors::{
11
12
  pub use sheet::{CalamineSheet, SheetMetadata, SheetTypeEnum, SheetVisibleEnum};
12
13
  pub use table::CalamineTable;
13
14
  pub use workbook::CalamineWorkbook;
15
+ pub use workbook_properties::WorkbookProperties;
@@ -10,7 +10,9 @@ use pyo3::prelude::*;
10
10
  use pyo3::types::PyType;
11
11
  use pyo3_file::PyFileLikeObject;
12
12
 
13
- use crate::{CalamineSheet, CalamineTable, Error, SheetMetadata, WorksheetNotFound};
13
+ use crate::{
14
+ CalamineSheet, CalamineTable, Error, SheetMetadata, WorkbookProperties, WorksheetNotFound,
15
+ };
14
16
 
15
17
  enum SheetsEnum {
16
18
  File(Sheets<BufReader<File>>),
@@ -65,6 +67,15 @@ impl SheetsEnum {
65
67
  }
66
68
  }
67
69
 
70
+ fn workbook_properties(&mut self) -> Result<WorkbookProperties, Error> {
71
+ match self {
72
+ SheetsEnum::File(f) => f.workbook_properties().map_err(Error::Calamine),
73
+ SheetsEnum::FileLike(f) => f.workbook_properties().map_err(Error::Calamine),
74
+ SheetsEnum::None => Err(Error::WorkbookClosed),
75
+ }
76
+ .map(WorkbookProperties::from)
77
+ }
78
+
68
79
  fn worksheet_range(&mut self, name: &str) -> Result<calamine::Range<calamine::Data>, Error> {
69
80
  match self {
70
81
  SheetsEnum::File(f) => f.worksheet_range(name).map_err(Error::Calamine),
@@ -265,6 +276,11 @@ impl CalamineWorkbook {
265
276
  }
266
277
  }
267
278
 
279
+ #[getter]
280
+ fn workbook_properties(&mut self, py: Python<'_>) -> PyResult<WorkbookProperties> {
281
+ py.detach(|| Ok(self.sheets.workbook_properties()?))
282
+ }
283
+
268
284
  #[pyo3(name = "get_table_by_name")]
269
285
  fn py_get_table_by_name(&mut self, py: Python<'_>, name: &str) -> PyResult<CalamineTable> {
270
286
  py.detach(|| self.get_table_by_name(name))
@@ -0,0 +1,140 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ use chrono::{DateTime, Datelike, FixedOffset, NaiveDateTime};
4
+ use pyo3::prelude::*;
5
+
6
+ /// A document property date, with a UTC offset if the file stores one.
7
+ #[derive(Clone, Debug, PartialEq, IntoPyObject)]
8
+ enum PropertyDate {
9
+ Aware(DateTime<FixedOffset>),
10
+ Naive(NaiveDateTime),
11
+ }
12
+
13
+ impl PropertyDate {
14
+ /// Parse a date such as "2024-01-15T08:30:00Z" (xlsx, xlsb, xls) or
15
+ /// "2024-06-20T14:22:00.123456789" (ods). Other formats, and years that
16
+ /// Python's `datetime` can't represent, return `None`.
17
+ fn parse(value: &str) -> Option<Self> {
18
+ let value = value.trim();
19
+ let date = match DateTime::parse_from_rfc3339(value) {
20
+ Ok(date) => PropertyDate::Aware(date),
21
+ Err(_) => NaiveDateTime::parse_from_str(value, "%Y-%m-%dT%H:%M:%S%.f")
22
+ .ok()
23
+ .map(PropertyDate::Naive)?,
24
+ };
25
+ let year = match &date {
26
+ PropertyDate::Aware(date) => date.year(),
27
+ PropertyDate::Naive(date) => date.year(),
28
+ };
29
+ (1..=9999).contains(&year).then_some(date)
30
+ }
31
+ }
32
+
33
+ /// Document properties of a workbook, such as the creator, title and company.
34
+ #[pyclass(eq, from_py_object)]
35
+ #[derive(Clone, Debug, Default, PartialEq)]
36
+ pub struct WorkbookProperties {
37
+ #[pyo3(get)]
38
+ creator: Option<String>,
39
+ #[pyo3(get)]
40
+ last_modified_by: Option<String>,
41
+ #[pyo3(get)]
42
+ created: Option<PropertyDate>,
43
+ #[pyo3(get)]
44
+ modified: Option<PropertyDate>,
45
+ #[pyo3(get)]
46
+ title: Option<String>,
47
+ #[pyo3(get)]
48
+ subject: Option<String>,
49
+ #[pyo3(get)]
50
+ description: Option<String>,
51
+ #[pyo3(get)]
52
+ keywords: Option<String>,
53
+ #[pyo3(get)]
54
+ category: Option<String>,
55
+ #[pyo3(get)]
56
+ content_status: Option<String>,
57
+ #[pyo3(get)]
58
+ revision: Option<String>,
59
+ #[pyo3(get)]
60
+ version: Option<String>,
61
+ #[pyo3(get)]
62
+ application: Option<String>,
63
+ #[pyo3(get)]
64
+ app_version: Option<String>,
65
+ #[pyo3(get)]
66
+ company: Option<String>,
67
+ #[pyo3(get)]
68
+ template: Option<String>,
69
+ #[pyo3(get)]
70
+ manager: Option<String>,
71
+ #[pyo3(get)]
72
+ custom_properties: BTreeMap<String, String>,
73
+ }
74
+
75
+ #[pymethods]
76
+ impl WorkbookProperties {
77
+ fn __repr__(&self, py: Python<'_>) -> PyResult<String> {
78
+ let fields = [
79
+ ("creator", self.creator.clone().into_pyobject(py)?),
80
+ (
81
+ "last_modified_by",
82
+ self.last_modified_by.clone().into_pyobject(py)?,
83
+ ),
84
+ ("created", self.created.clone().into_pyobject(py)?),
85
+ ("modified", self.modified.clone().into_pyobject(py)?),
86
+ ("title", self.title.clone().into_pyobject(py)?),
87
+ ("subject", self.subject.clone().into_pyobject(py)?),
88
+ ("description", self.description.clone().into_pyobject(py)?),
89
+ ("keywords", self.keywords.clone().into_pyobject(py)?),
90
+ ("category", self.category.clone().into_pyobject(py)?),
91
+ (
92
+ "content_status",
93
+ self.content_status.clone().into_pyobject(py)?,
94
+ ),
95
+ ("revision", self.revision.clone().into_pyobject(py)?),
96
+ ("version", self.version.clone().into_pyobject(py)?),
97
+ ("application", self.application.clone().into_pyobject(py)?),
98
+ ("app_version", self.app_version.clone().into_pyobject(py)?),
99
+ ("company", self.company.clone().into_pyobject(py)?),
100
+ ("template", self.template.clone().into_pyobject(py)?),
101
+ ("manager", self.manager.clone().into_pyobject(py)?),
102
+ ];
103
+ let mut parts = Vec::new();
104
+ for (name, value) in fields {
105
+ if !value.is_none() {
106
+ parts.push(format!("{name}={}", value.repr()?));
107
+ }
108
+ }
109
+ if !self.custom_properties.is_empty() {
110
+ let custom = (&self.custom_properties).into_pyobject(py)?;
111
+ parts.push(format!("custom_properties={}", custom.repr()?));
112
+ }
113
+ Ok(format!("WorkbookProperties({})", parts.join(", ")))
114
+ }
115
+ }
116
+
117
+ impl From<calamine::WorkbookProperties> for WorkbookProperties {
118
+ fn from(props: calamine::WorkbookProperties) -> Self {
119
+ WorkbookProperties {
120
+ creator: props.creator,
121
+ last_modified_by: props.last_modified_by,
122
+ created: props.created.as_deref().and_then(PropertyDate::parse),
123
+ modified: props.modified.as_deref().and_then(PropertyDate::parse),
124
+ title: props.title,
125
+ subject: props.subject,
126
+ description: props.description,
127
+ keywords: props.keywords,
128
+ category: props.category,
129
+ content_status: props.content_status,
130
+ revision: props.revision,
131
+ version: props.version,
132
+ application: props.application,
133
+ app_version: props.app_version,
134
+ company: props.company,
135
+ template: props.template,
136
+ manager: props.manager,
137
+ custom_properties: props.custom_properties.into_iter().collect(),
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,156 @@
1
+ from datetime import datetime, timezone
2
+ from io import BytesIO
3
+ from pathlib import Path
4
+ from zipfile import ZipFile
5
+
6
+ import pytest
7
+ from python_calamine import CalamineWorkbook, WorkbookClosed, WorkbookProperties
8
+
9
+ PATH = Path(__file__).parent / "data"
10
+
11
+
12
+ def test_xlsx_workbook_properties():
13
+ props = CalamineWorkbook.from_path(
14
+ PATH / "workbook_properties.xlsx"
15
+ ).workbook_properties
16
+
17
+ assert isinstance(props, WorkbookProperties)
18
+ assert props.creator == "Test Creator"
19
+ assert props.last_modified_by == "Last Modifier"
20
+ assert props.created == datetime(2024, 1, 15, 8, 30, tzinfo=timezone.utc)
21
+ assert props.modified == datetime(2024, 6, 20, 14, 22, tzinfo=timezone.utc)
22
+ assert props.title == "Workbook Title"
23
+ assert props.subject == "Test Subject"
24
+ assert props.description == "A test workbook"
25
+ assert props.keywords == "test, calamine"
26
+ assert props.category == "Testing"
27
+ assert props.content_status == "Draft"
28
+ assert props.revision == "3"
29
+ assert props.version == "1.2"
30
+ assert props.application == "Microsoft Excel"
31
+ assert props.app_version == "16.0300"
32
+ assert props.company == "Contoso & Co"
33
+ assert props.template == "Book.xltx"
34
+ assert props.manager == "Jane Doe"
35
+ assert props.custom_properties == {"Department": "Finance", "Reviewed": "true"}
36
+
37
+
38
+ def test_ods_workbook_properties():
39
+ props = CalamineWorkbook.from_path(
40
+ PATH / "workbook_properties.ods"
41
+ ).workbook_properties
42
+
43
+ assert props.creator == "Test Creator"
44
+ assert props.last_modified_by == "Last Modifier"
45
+ assert props.created == datetime(2024, 1, 15, 8, 30)
46
+ assert props.modified == datetime(2024, 6, 20, 14, 22, 0, 123456)
47
+ assert props.title == "Workbook Title"
48
+ assert props.subject == "Test Subject"
49
+ assert props.description == "A test workbook"
50
+ assert props.keywords == "test, calamine"
51
+ assert props.revision == "3"
52
+ assert props.application is not None
53
+ assert props.application.startswith("LibreOffice/24.2")
54
+ assert props.company is None
55
+ assert props.manager is None
56
+ assert props.custom_properties == {
57
+ "Department": "Finance & Ops",
58
+ "Reviewed": "true",
59
+ }
60
+
61
+
62
+ @pytest.mark.parametrize(
63
+ ("file", "modified", "application"),
64
+ [
65
+ (
66
+ "any_sheets.xlsx",
67
+ datetime(2023, 7, 28, 16, 31, 17, tzinfo=timezone.utc),
68
+ "Microsoft Excel",
69
+ ),
70
+ (
71
+ "any_sheets.xlsb",
72
+ datetime(2023, 7, 28, 16, 31, 46, tzinfo=timezone.utc),
73
+ "Microsoft Excel",
74
+ ),
75
+ (
76
+ "any_sheets.xls",
77
+ datetime(2023, 7, 28, 16, 31, 33, tzinfo=timezone.utc),
78
+ "Microsoft Excel",
79
+ ),
80
+ (
81
+ "any_sheets.ods",
82
+ datetime(2023, 7, 28, 16, 32, 8, tzinfo=timezone.utc),
83
+ "MicrosoftOffice/16.0 MicrosoftExcel/CalculationVersion-14420",
84
+ ),
85
+ ],
86
+ )
87
+ def test_workbook_properties_all_formats(file, modified, application):
88
+ props = CalamineWorkbook.from_path(PATH / file).workbook_properties
89
+
90
+ assert props.creator == "Алена"
91
+ assert props.last_modified_by == "Алена"
92
+ assert props.created == datetime(2023, 7, 28, 16, 28, 6, tzinfo=timezone.utc)
93
+ assert props.modified == modified
94
+ assert props.application == application
95
+ assert props.title is None
96
+ assert props.custom_properties == {}
97
+
98
+
99
+ @pytest.mark.parametrize(
100
+ "file",
101
+ ["any_sheets.xlsx", "any_sheets.xlsb", "any_sheets.xls", "any_sheets.ods"],
102
+ )
103
+ def test_workbook_properties_from_filelike(file):
104
+ with open(PATH / file, "rb") as f:
105
+ props = CalamineWorkbook.from_filelike(BytesIO(f.read())).workbook_properties
106
+
107
+ assert props == CalamineWorkbook.from_path(PATH / file).workbook_properties
108
+ assert props.creator == "Алена"
109
+
110
+
111
+ def test_workbook_properties_missing_fields():
112
+ props = CalamineWorkbook.from_path(PATH / "base.xlsx").workbook_properties
113
+
114
+ assert props.creator is None
115
+ assert props.last_modified_by is None
116
+ assert props.created == datetime(2021, 9, 17, 15, 27, 18, tzinfo=timezone.utc)
117
+ assert props.app_version == "16.0300"
118
+
119
+
120
+ def test_workbook_properties_unrepresentable_dates():
121
+ # Python's datetime has no year 0, so these dates are None.
122
+ buffer = BytesIO()
123
+ with ZipFile(PATH / "base.xlsx") as src, ZipFile(buffer, "w") as dst:
124
+ for item in src.infolist():
125
+ data = src.read(item)
126
+ if item.filename == "docProps/core.xml":
127
+ data = data.replace(b"2021-09-17T15:27:18Z", b"0000-01-01T00:00:00Z")
128
+ data = data.replace(b"2025-04-13T17:29:27Z", b"0000-01-01T00:00:00")
129
+ dst.writestr(item, data)
130
+ buffer.seek(0)
131
+
132
+ props = CalamineWorkbook.from_filelike(buffer).workbook_properties
133
+
134
+ assert props.created is None
135
+ assert props.modified is None
136
+ assert repr(props) == "WorkbookProperties(app_version='16.0300')"
137
+
138
+
139
+ def test_workbook_properties_repr():
140
+ props = CalamineWorkbook.from_path(PATH / "base.xls").workbook_properties
141
+
142
+ assert repr(props) == (
143
+ "WorkbookProperties("
144
+ "created=datetime.datetime(2021, 9, 17, 5, 27, 18, tzinfo=datetime.timezone.utc), "
145
+ "modified=datetime.datetime(2025, 4, 13, 18, 43, 16, tzinfo=datetime.timezone.utc), "
146
+ "revision='18', app_version='16.0000', "
147
+ "custom_properties={'AppVersion': '15.0000'})"
148
+ )
149
+
150
+
151
+ def test_workbook_properties_closed():
152
+ reader = CalamineWorkbook.from_path(PATH / "base.xlsx")
153
+ reader.close()
154
+
155
+ with pytest.raises(WorkbookClosed):
156
+ reader.workbook_properties