Metadata-Version: 2.4
Name: minchin.django.excel
Version: 1.2.0
Summary: Load Excel files into your Django database.
Author-email: William Minchin <w_minchin@hotmail.com>
Maintainer-email: William Minchin <w_minchin@hotmail.com>
License-Expression: MIT
Project-URL: Repository, https://github.com/minchinweb/minchin.django.excel
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Description-Content-Type: text/markdown
License-File: License.txt
Requires-Dist: django>=4.2
Requires-Dist: django-auto-prefetch>=0.0.6
Requires-Dist: ciso8601>=2.2.0
Requires-Dist: dateparser>=1.1.1
Requires-Dist: numpy>=1.22.4
Requires-Dist: pandas>=1.4.2
Requires-Dist: colorama>=0.4.4
Requires-Dist: minchin.text>=6.1.0
Requires-Dist: django-prettyjson>=0.4.1
Requires-Dist: django-related-admin==1.0.1
Requires-Dist: openpyxl>=3.0.10
Provides-Extra: dev
Requires-Dist: invoke; extra == "dev"
Requires-Dist: minchin.releaser; extra == "dev"
Requires-Dist: isort; extra == "dev"
Requires-Dist: black; extra == "dev"
Dynamic: license-file

# Minchin.Django.Excel

This is a Django app designed to allow you to push the contents of Excel
workbooks to your Django database. I packaged it because while it seems like it
should be simple, it involved many more moving pieces (including management
commands, templates, template tags, admin pagination, etc.) than I initially
thought it should.


## Installation

The package is installable via `pip`:

```sh
pip install minchin.django.excel
```

This will also install all the required dependencies (of which there are
many...).

From there, you need to add it to your list of installed apps in your Django
`settings.py`:

```py
# settings.py

INSTALLED_APPS = [
  # first in line
  "related_admin",  # for minchin.django.excel

  # others...
  "minchin.django.excel",
  "prettyjson",  # for minchin.django.excel
]

# other settings...
```

Second, ensure that your `TEMPLATES` setting contains a DjangoTemplates backend
whose `APP_DIRS` options is set to `True`:

```py
# settings.py

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "APP_DIRS": True,
        # ...
    }
]

# other settings...
```

and then run the included database migrations:

```sh
python manage.py migrate
```

### Loading Excel Data

There are two loaders. Both read **cached values, not formulas**
(`data_only`: what Excel last saved, which matters when a formula points at
another file you don't have). They differ in what they keep of an empty cell,
and in how `row_count` and `col_count` are counted. Neither is a wrapper
around the other.

#### Management command: `load_excel`

```sh
python manage.py load_excel <excel_file.xlsx> [<excel_file.xlsx> ...]
```

File names can include wildcards (e.g. `reports/*.xlsx`). Parsing is done with
pandas (`read_excel`), which uses openpyxl with `data_only`. Each file is
stored as a `Workbook`, with one `Sheet` per tab, and one `Row` per row of
the dataframe — **including blank rows, and including empty cells as
`null`**. `row_count` and `col_count` are that dataframe's shape (every row
and column pandas read, empty ones included). Row data is JSON keyed by the
Excel column name (`{"A": ..., "B": ...}`). `Row.index` is the zero-based
position in that dataframe.

If the file is already in the database (matched by its MD5 hash), or a
different file with the same name is, you'll be asked whether to replace it.
To answer ahead of time:

- `--skip-existing` (`-s`): don't reload files already in the database, and
  keep existing workbooks with the same name alongside the new one.
- `--replace-existing` (`-r`): replace existing workbooks, whether matched by
  hash or by name.

Each file is loaded in a single transaction, so a file that can't be read
doesn't leave anything behind (or delete the workbook it was replacing).

#### In code: `store_workbook`

```py
from minchin.django.excel.store import store_workbook

workbook = store_workbook(file_obj, "report.xlsx", replace=False, mtime=None)
```

`file_obj` is anything binary you can `read()` and `seek()` on, including a
Django `UploadedFile`. openpyxl loads it with `read_only=True`,
`data_only=True`, and `keep_links=False`.

Only **non-empty** cells are stored. Strings are stripped. `""` and Excel
errors (`#REF!`, `#N/A`, `#VALUE!`, `#DIV/0!`, `#NAME?`, `#NUM!`, `#NULL!`,
`#SPILL!`, `#CALC!`) are treated as missing and left out. A numeric `0` is
kept. Completely empty rows are skipped, but `Row.index` stays the
**zero-based Excel row index**: data on Excel rows 1 and 3 is stored as
indexes 0 and 2. `row_count` is the last occupied Excel row, not the number
of `Row` objects. `col_count` is the highest occupied column. Sheet names are
truncated to 63 characters.

A file whose md5 is already loaded raises `DuplicateWorkbookError` (the
message contains "Same contents"), unless `replace=True`, which deletes the
old workbook (and, by cascade, what was derived from it) and loads this one.
The check, the delete, and the insert are one transaction.

`compare_to_loaded` and `earlier_versions` (same module) describe how a file
differs from what is already stored. `clean_cell` is the per-value cleaner
`store_workbook` uses.

#### Reading stored rows

```py
from minchin.django.excel.read import SheetTable, table_for, pick
```

`table_for(workbook, sheet_name)` returns a `SheetTable`, or `None`. Row
numbers on it are Excel's (from 1). `header_map` names columns, turning a
repeated header into `"Group / Header"` when a group row makes that unique,
otherwise `"Header (2)"`. `records` yields `(row_number, {header: value})`
and skips rows whose required headers are all blank. `pick`, `normalize_label`,
`to_decimal`, `to_int`, `to_str`, `to_date`, and `to_bool` are in the same
module.

These names are not re-exported from `minchin.django.excel` itself; import
them from `store` or `read`. `SheetTable` reads rows from either loader.


### Django Admin Site

There are also several helpers so that you can see the loaded data on the
built-in Django admin site. However, you'll need to register them to your admin
site:

```py
# admin.py
from django.contrib import admin

from minchin.django.excel.admin import WorkbookAdmin, SheetAdmin, RowAdmin
from minchin.django.excel.models import Workbook, Sheet, Row

admin.site.register(Workbook, WorkbookAdmin)
admin.site.register(Sheet, SheetAdmin)
admin.site.register(Row, RowAdmin)
```

The Sheet page shows its rows in a paginated inline, `RowInline`. That's built
on `minchin.django.excel.utils.PaginationInline`, a `TabularInline` you can use
for your own models too:

- `per_page` (default 20) rows are shown per page, and `max_show_all`
  (default 200) is the most that the "Show all" link will show at once.
- The page is set by the `<prefix>-p` query parameter (e.g. `?row_set-p=3`),
  so several paginated inlines on one page are paged independently.
- The inline (or its model) needs an `ordering`, so rows don't move between
  pages; otherwise `ImproperlyConfigured` is raised.


## License

The code is licensed under the MIT license. See attached `License.txt`


## Changelog

### Version 1.2.0 -- Nov. 10, 2026

- `minchin.django.excel.store`: `store_workbook` (openpyxl, non-empty cells
  only, duplicate md5 raises `DuplicateWorkbookError` unless `replace`),
  `compare_to_loaded`, `earlier_versions`, `clean_cell`
- `minchin.django.excel.read`: `SheetTable`, `table_for`, header names
  (`"Group / Header"`, `"Header (2)"`), `pick`, and `to_decimal` / `to_int` /
  `to_str` / `to_date` / `to_bool`
- `load_excel` is unchanged: pandas, every cell including nulls, dataframe
  shape for `row_count` and `col_count`. Both loaders use cached values
  (`data_only`), not formulas.

### Version 1.1.0 -- Oct. 5, 2026

In particular, this release is to keep this working (without errors) in Django
5.2 (and newer).

- remove legacy `jasonize-rows` management command
- fix the Sheet admin page crashing on Django 5.0+, and rework the paginated
  inline: 1-based pages, a page parameter per inline (`<prefix>-p`), elided
  page links, a limit on "Show all" (`max_show_all`), and its CSS is now
  loaded as a static file
- **breaking:** remove the `back_url`, `forward_url`, and `make_range` template
  tags (from `excel_tags`), replaced by `inline_pagination`
- `django.contrib.humanize` is no longer required
- `load_excel`: the same-filename prompt now respects `--skip-existing` and
  `--replace-existing`; files are loaded in a single transaction; rows are
  inserted in bulk; warn when a file pattern matches nothing
- `from_timestamp`: integer timestamps are now read as UTC (they were read in
  local time); unparseable strings raise `ValueError`; aware strings work
- the JSON encoder handles numpy booleans
- require Django 4.2 or newer; drop the unused `psycopg2` and `pytz`
  dependencies
- fix the readme and license filenames in the package metadata
- add tests

### Version 1.0.0 -- Dec. 12, 2025

- initial public release

## Contributions

Contributions are welcome, however the scope of the project is intentionally
limited.

To set up a development environment and run the tests:

```sh
pip install -e .[dev]
invoke load-tests
```

Code is formatted with `isort` and `black`.
