question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Workbook is not closed

See original GitHub issue

This is a documentation issue.

On the Working with Dates and Time page, there is an example that does not contain workbook.close() at the end. This can lead to a RuntimeError:

Exception RuntimeError: RuntimeError('sys.meta_path must be a list of import hooks',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x10617f150>> ignored

Reproduceable using XlsxWriter version 0.5.5 and Python 2.7.5. Here’s the code that reproduces the problem:

from datetime import datetime
import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('datetimes.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

# Expand the first columns so that the dates are visible.
worksheet.set_column('A:B', 30)

# Write the column headers.
worksheet.write('A1', 'Formatted date', bold)
worksheet.write('B1', 'Format', bold)

# Create a datetime object to use in the examples.

date_time = datetime.strptime('2013-01-23 12:30:05.123',
                              '%Y-%m-%d %H:%M:%S.%f')

# Examples date and time formats.
date_formats = (
    'dd/mm/yy',
    'mm/dd/yy',
    'dd m yy',
    'd mm yy',
    'd mmm yy',
    'd mmmm yy',
    'd mmmm yyy',
    'd mmmm yyyy',
    'dd/mm/yy hh:mm',
    'dd/mm/yy hh:mm:ss',
    'dd/mm/yy hh:mm:ss.000',
    'hh:mm',
    'hh:mm:ss',
    'hh:mm:ss.000',
)

# Start from first row after headers.
row = 1

# Write the same date and time using each of the above formats.
for date_format_str in date_formats:

    # Create a format for the date or time.
    date_format = workbook.add_format({'num_format': date_format_str,
                                      'align': 'left'})

    # Write the same date using different formats.
    worksheet.write_datetime(row, 0, date_time, date_format)

    # Also write the format string for comparison.
    worksheet.write_string(row, 1, date_format_str)

    row += 1 

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:13 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
jmcnamaracommented, Jun 5, 2014

That makes sense to split it in two.

For item 1 the docs should just state that an explicit close is always required and all examples should have it included.

For reference here are the docs for close() in the Lua version of the module.

For 2 I tried very quickly to use weakref without success. A more quick and dirty way might be to catch the exception in the workbook destructor and issue a warning. Something like the following patch:

diff --git a/xlsxwriter/workbook.py b/xlsxwriter/workbook.py
index 882f0f2..62d767b 100644
--- a/xlsxwriter/workbook.py
+++ b/xlsxwriter/workbook.py
@@ -126,8 +126,12 @@ class Workbook(xmlwriter.XMLwriter):

     def __del__(self):
         """Close file in destructor if it hasn't been closed explicitly."""
-        if not self.fileclosed:
-            self.close()
+        try:
+            if not self.fileclosed:
+                self.close()
+        except:
+            raise Exception("Exception caught in workbook destructor. "
+                            "Explicit close() may be required for workbook.")

Which would give an exception like this for the example above:

$ python date_example.py
Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() may be required for workbook.',) 
in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x103297d50>> ignored

This was just a quick fix and you may have some better suggestions.

Note, a little unfortunately the exception isn’t always RuntimeError or the try could be more explicit. On Windows and possibly some other systems/programs it raises a LookupError exception.

If you would like to tackle either of these that would be fine by me (as I said I have a bit of a backlog at the moment). If not I’ll try roll them into the next release.

0reactions
jmcnamaracommented, Jul 23, 2014

@jkyeung

That should be explicit.

Thanks John. Well spotted. That is fixed now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Resource leak: workbook is never closed warning when using ...
workbook.close() is not available as a method to close the workbook afterwards. Any ideas of how can I let garbage collection take the...
Read more >
Close workbook but not Excel (2013, 2016 and up) - AuditExcel
One of the problems with the new versions of Excel is that you often need to close Excel down completely to start afresh....
Read more >
Excel will not close workbook when clicking X if more than 1 ...
Excel will not close workbook when clicking X if more than 1 workbook is open. I have tried everything that I have found...
Read more >
org.apache.poi.xssf.usermodel.XSSFWorkbook.close java ...
Resource leak: workbook is never closed warning when using Apache. ... Book2.xlsx by Excel // The linkExternalWorkbook has not yet been implemented: SEE...
Read more >
Close workbook but not Excel so that you can easily open a ...
00:00 Excel closes down completely when you close a workbook00:27 Close a workbook but not the whole of Excel- menu option00:42 Shortcut to ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found