File: example_inheritance2.rst

package info (click to toggle)
xlsxwriter 3.1.9-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 56,308 kB
  • sloc: python: 51,511; javascript: 7,768; sh: 284; makefile: 195; perl: 75
file content (38 lines) | stat: -rw-r--r-- 1,546 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
.. SPDX-License-Identifier: BSD-2-Clause
   Copyright 2013-2023, John McNamara, jmcnamara@cpan.org

.. _ex_inheritance2:

Example: Advanced example of subclassing
========================================

Example of how to subclass the Workbook and Worksheet objects. See also the
simpler :ref:`inheritance1.py <ex_inheritance1>` example.

In this example we see an approach to implementing a simulated autofit in a
user application. This works by overriding the ``write_string()`` method to
track the maximum width string in each column and then set the column widths
when closing the workbook.

Some notes on this:

* **This isn't a fully functional autofit example** (as shown by the longer
  strings in the screen shot). It is only a proof or concept or a framework to
  try out solutions. See the the worksheet :func:`autofit` method instead.

* The hard part is coming up with an accurate (or mainly accurate)
  ``excel_string_width()`` function. One possibility is to use the PIL
  `ImageFont()
  <https://pillow.readthedocs.io/en/latest/reference/ImageFont.html>`_ method
  and convert the pixel width back to a character width.

* A more rigorous approach would have to consider font sizes, bold, italic,
  etc.
* The ``set_column()`` calls in ``close()`` will override any others set by the
  user. They also don't set any column formats.
* It doesn't work for horizontal merge ranges.
* There are probably some other corner cases hiding here.

.. image:: _images/inheritance2.png

.. literalinclude:: ../../../examples/inheritance2.py