A Python module for creating Excel XLSX files.

Overview

XlsxWriter

XlsxWriter is a Python module for writing files in the Excel 2007+ XLSX file format.

XlsxWriter can be used to write text, numbers, formulas and hyperlinks to multiple worksheets and it supports features such as formatting and many more, including:

  • 100% compatible Excel XLSX files.
  • Full formatting.
  • Merged cells.
  • Defined names.
  • Charts.
  • Autofilters.
  • Data validation and drop down lists.
  • Conditional formatting.
  • Worksheet PNG/JPEG/BMP/WMF/EMF images.
  • Rich multi-format strings.
  • Cell comments.
  • Integration with Pandas.
  • Textboxes.
  • Support for adding Macros.
  • Memory optimization mode for writing large files.

It supports Python 2.7, 3.4+ and PyPy and uses standard libraries only.

Here is a simple example:

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

https://raw.github.com/jmcnamara/XlsxWriter/master/dev/docs/source/_images/demo.png

See the full documentation at: https://xlsxwriter.readthedocs.io

Release notes: https://xlsxwriter.readthedocs.io/changes.html

Comments
  • Feature request: Separate data and formatting

    Feature request: Separate data and formatting

    It is a planned feature to allow cell data and formatting to be applied separately.

    This would also allow format copying and merging of formats to be applied to a range of cells.

    However, it is non-trivial to implement correctly and there are no implied timelines on when or if this feature will be available.

    John

    feature request medium term 
    opened by jmcnamara 41
  • xlsxwriter/workbook.py causes ValueError('ZIP does not support timestamps before 1980')

    xlsxwriter/workbook.py causes ValueError('ZIP does not support timestamps before 1980')

    Hi,

    I am using XlsxWriter to simply execute the documented basic creation of an xlsx as per: http://xlsxwriter.readthedocs.io/example_pandas_simple.html

    but it reports an error:

    python3 test.py
    Traceback (most recent call last):
      File "test.py", line 22, in <module>
        writer.save()
      File "/usr/local/lib/python3.6/site-packages/pandas/io/excel.py", line 1732, in save
        return self.book.close()
      File "/usr/local/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 311, in close
        self._store_workbook()
      File "/usr/local/lib/python3.6/site-packages/xlsxwriter/workbook.py", line 658, in _store_workbook
        xlsx_file.write(os_filename, xml_filename)
      File "/usr/local/lib/python3.6/zipfile.py", line 1594, in write
        zinfo = ZipInfo.from_file(filename, arcname)
      File "/usr/local/lib/python3.6/zipfile.py", line 496, in from_file
        zinfo = cls(arcname, date_time)
      File "/usr/local/lib/python3.6/zipfile.py", line 338, in __init__
        raise ValueError('ZIP does not support timestamps before 1980')
    ValueError: ZIP does not support timestamps before 1980
    
    

    I am using Python version 3.6.5 and XlsxWriter 1.0.5 under a docker image with debian jessie.

    The workaround I've managed is to edit the file https://github.com/jmcnamara/XlsxWriter/blob/master/xlsxwriter/workbook.py

    and change twice "1980" with "1990". Then there is no error and it works perfectly.

    Not the most elegant and not the root fix of the problem but it does the job. Reporting this out as ye would probably be able to figure out why and solve it for other users permanently.

    Thanks for the libraries John, they all are awesome!

    ready to close under investigation 
    opened by salvor-hardin 36
  • Feature request: Add Value From Cells for series data_labels source

    Feature request: Add Value From Cells for series data_labels source

    Add Value From Cells for series data_labels source

    Currently, chart.add_series data_labels only supports:

    • value
    • category
    • series_name
    • position
    • leader_lines
    • percentage

    It would be great to select the source of the data, as is possible in Excel using "Value From Cells" in the label options formatting dialog.

    My particular need is for scatter charts.

    Thanks

    feature request medium term 
    opened by technodoug 32
  • Feature request: Support for copying the Format instance

    Feature request: Support for copying the Format instance

    Is it possible to add the subject? So that when we have a "general" format for the data processed in a loop, we could e.g. assign a separate Format instance to the cells that we want to write the hyperlinks into.

    feature request medium term 
    opened by croshchupkin 31
  • Issue adding images become squeezed

    Issue adding images become squeezed

    Hi,

    I am trying to insert images in spreadsheets. The code works fine, however the images are squeezed. When I open Excel / Format Shape / Size & Properties / Size, the scaling ratios seem rather insane:

    • 339%, 100% for image 1
    • 511%, 100% for image 2
    • 550%, 100% for image 3

    When I press the Reset button in that panel, the image go back to a reasonnable size.

    When I try to change the scale factor, as in the code below, I have to put unreasonnably small numbers for one of the axis, like 0.08, but even that does not work reliably and seems image dependent.

    I am at a lost as to what is happening.

    I am using Python 3.6.8 and XlsxWriter 1.2.7 and Excel 2019 version 2003 (Build 12624.20466).

    Here is some code that demonstrates the problem:

            # img = Image.open(path)
            # w, h = img.size
            # scale = min((240.0 / w, 240.0 / h))
    
            self.worksheet.insert_image(self.row, self.col, path, {
                # 'x_offset': 20, 'y_offset': 20,
                # 'x_scale': 0.8, 'y_scale': 0.08,
            })
    
    question awaiting user feedback 
    opened by caramdache 26
  • Plans on Implementing Inserting Image in Footer?

    Plans on Implementing Inserting Image in Footer?

    In the documentation under the worksheet.insert_image() method, you mention that inserting an image into the worksheet footer is not supported. Are there any plans on implementing this? I know it would be useful, for example, for putting a company logo in the footer.

    feature request ready to close 
    opened by NinjaMeTimbers 25
  • unable to close(); saves a corrupted workbook

    unable to close(); saves a corrupted workbook

    import xlsxwriter
    
    workbook = xlsxwriter.Workbook('hello.xlsx')
    worksheet = workbook.add_worksheet()
    
    worksheet.write('A1', 'Hello world')
    
    workbook.close()
    
    

    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\DOUGHE~1.ROS\AppData\Local\Temp\tmpnpp39a_c'

    
    I was able to write excel files yesterday; today my day began with this issue and I was not able to resolve.  I was hoping someone here may be of assistance.  
    
    If I run workbook.close() again, I do not receive the error, but the .xlsx file does not open and says it is corrupted.
    
    I'm not sure what happened.  I may have have closed/exited the program incorrectly.  I've read of the importance of using workbook.close(), did I create a 'write to excel ghost' living in the purgatory of my temp folder?  This issue now extends to pandas .to_excel() as well.  I am able to write to csv.   
    
    I've restarted, reinstalled anaconda +packages, deleted all the tmp files in the temp folder, however I still receive this error.  Any help would be greatly appreciated. Thank you.
    
    
    
    windows 10
    python 2.7, 3.6, 3.7 (I had base install of anaconda py 2.7, with an additional environment of 3.6.  Reinstalled anaconda with python 3.7, 64bit.  Issue happened with all three)
    question 
    opened by jefdough 20
  • Issue with protect sheet and sorting

    Issue with protect sheet and sorting

    Hi,

    I am using XlsxWriter to do protect sheet with sorting and autofliter options available, but it appears sorting is not working.

    I am using Python version 3.5.2 and XlsxWriter 1.0.3.

    
    import xlsxwriter
    import uuid
    
    workbook = xlsxwriter.Workbook('test.xlsx')
    worksheet = workbook.add_worksheet()
    
    for x in range(0,5):
    	worksheet.write(0, x, 'Header_' + str(x))
    
    for y in range(1,5):
    	for x in range(0,5):
    		worksheet.write(y, x, str(uuid.uuid4()))
    	
    worksheet.autofilter(0, 0, 4, 4)
    worksheet.protect('pwd', {'sort': 1,'autofilter': 1,})
    
    workbook.close()
    
    
    feature request 
    opened by arkuzin 19
  • Issue with stretched images

    Issue with stretched images

    When inseret image in cell (JPG, PNG all supported), that this image Stretched width. Example Code:

    from xlsxwriter.workbook import Workbook
    
    from PIL import Image
    import urllib
    
    url_img = u'https://www.filepicker.io/api/file/XUCKqJyLSXGbF6a6XyfL'
    img_name = 'test_name.jpg'
    urllib.urlretrieve(url_img, img_name) # Save image
    
    # Convert image
    img = Image.open(img_name)
    img = img.resize((115, 115), Image.ANTIALIAS)
    img.info["dpi"] = (96, 96)
    img_name = "{}_resize.{}".format('test_name_resize', img_name.split('.')[-1])
    img.save(img_name,)
    
    workbook = Workbook('out.xlsx')
    worksheet = workbook.add_worksheet()
    
    worksheet.set_row(2, 95)
    worksheet.set_column(2, 2, 12)
    
    worksheet.insert_image(2, 2, img_name, {'y_offset': 5, })
    workbook.close()
    

    Result: bug

    Correct Version correct

    bug 
    opened by jmcnamara 19
  • Deprecation notice for Python 2.7 (and 3.5) support. Target July 2021

    Deprecation notice for Python 2.7 (and 3.5) support. Target July 2021

    I have just added the following notice to the Changes page of the XlsxWriter docs:

    Deprecation Notice: Python 2.7 reached the end of its life on January 1st, 2020 and is no longer being supported in the community. XlsxWriter support for Python 2.7 will end by mid-year 2021 (probably in July 2021). No new features or fixes for Python 2.7 will be added to XlsxWriter after that date/release.

    If anyone has any concerns about this please raise them now.

    awaiting user feedback 
    opened by jmcnamara 18
  • Feature request: Allow identifying formats by name

    Feature request: Allow identifying formats by name

    Today, when dealing with complex an multiple formats, I use the following piece of code to be able to retrieve them at the time to write data :

    def register_formats(wb, d):
        return {k: wb.add_format(v) if v is not None else v for k, v in d.items()}
    
    #my_formats d parameter simplified for readability sake
    my_formats = register_formats(workbook, {
            'error':  {'bg_color': '#cc0000'},
            'warning': {'bg_color': '#ffff00'},
            'ok': None})
    
    # Much farther in the program ...
    
    ws = wb.add_worksheet()
    ws.write(0,0,"text", my_formats['error'])
    
    

    but then one has to pass this my_format dictionary around.

    I suggest to extend the workbook interface with an optional ref parameter, and then in the write functions be able to give the reference of the format rather than the format itself. It would result in something like :

    wb.add_format({'bg_color': '#cc0000'}, ref="error")
    
    #####
    
    ws.write(0,0,"text", format_ref="error")
    
    

    I can propose an implementation if that helps.

    feature request medium term 
    opened by aubanel 18
  • feature request: auto column width

    feature request: auto column width

    Feature Request

    We don't see a option for setting the width of columns automatically accordingly to column values. It will be good feature to have. I have seen a workaround for this in below post https://stackoverflow.com/questions/29463274/simulate-autofit-column-in-xslxwriter

    feature request short term 
    opened by rahul-philips 1
  • feature request:  Can you add a slicer when `worksheet.add_table` API

    feature request: Can you add a slicer when `worksheet.add_table` API

    Feature Request

    image

    options = {
        "data": data,
        "slicer": [
            {"column": "Column1", "location": "A1"},
            {"column": "Column2", "location": "C1"},
        ]
    }
    
    or 
    
    options = {
        'data': data,
        'columns': [
            {'header': 'Product', 'slicer': 'A1'},
            {'header': 'Quarter 1'},
            {'header': 'Quarter 2'},
            {'header': 'Quarter 3'},
            {'header': 'Quarter 4'},
        ]
    }
    worksheet.add_table('B3:F7', {options})
    

    In this way, you can initially realize the function of the pivot table.

    At present, I think the method is to rewrite the Workbook, Worksheet for simple implementation, but I don't know how to add slicer1.xml file

    image

    feature request someday 
    opened by vuesets 1
  • Rust port of xlsxwriter

    Rust port of xlsxwriter

    I have started a Rust port of XlsxWriter called rust_xlsxwriter. See the following for information:

    Any feedback, early usage, or reviews welcome.

    feature request 
    opened by jmcnamara 0
  • Added unique return codes

    Added unique return codes

    Added return codes as anticipated in https://github.com/jmcnamara/XlsxWriter/issues/884

    This pull request is the one including the new modifications to main introduced after PR #887

    The return codes are now an Enum inheriting from str, so an explicative message can be automatically printed without helper functions.

    The return codes are in file returncodes.py

    84 new dedicated tests are added to test/core/test_returncodes.py

    Documentation has been updated

    At the end I run make test, make test_flake8 and make docs. All tests succeeded and flake8 did not report anything. Development and tests were done with Python 3.9.2

    opened by fra87 6
  • Updated xl_col_to_name() method to add recursion

    Updated xl_col_to_name() method to add recursion

    This PR links to issue #881 which I opened recently – I propose that the xl_col_to_name() function (here) can be improved to a recursive function to bring it to O(log26 n) time complexity and O(1) auxiliary space.

    I created a GitHub Gist here to compare the times of the older and the newer functions I propose with %timeit. IPython defaults to n = 100 anyway. The updated function is faster.

    Writing tests

    I haven't written any unit tests to resolve the issue as of now – I'm not aware of how to do so, but I can learn.

    opened by agriyakhetarpal 15
  • feature request: color chart lines with gradients

    feature request: color chart lines with gradients

    Feature Request

    I would like to color the chart lines with gradients like other chart elements.

    Example: spectrumplot.add_series({ 'categories': '=Spektrum!$B$1:$CD$1', 'values': '=Spektrum!$B$2:$CD$2', 'gradient': { 'colors': ['#B000AE', '#FF00FC', '#0000FF', '#00FFFF', '#00FF00', '#FFFF00', '#FFA200', '#FF0000', '#000000'], 'positions': [0, 5, 17, 26, 37, 50, 56, 76, 100], } })

    feature request medium term 
    opened by huejan 0
Owner
John McNamara
anyone lived in a pretty how town with up so floating many bells down
John McNamara
An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files.

foamTEX An open source utility for creating publication quality LaTex figures generated from OpenFOAM data files. Explore the docs » Report Bug · Requ

null 1 Dec 19, 2021
DocumentPy is a Python application that runs in a command-line interface environment, made for creating HTML documents.

DocumentPy DocumentPy is a Python application that runs in a command-line interface environment, made for creating HTML documents. Usage DocumentPy, a

Lotus 0 Jul 15, 2021
A module filled with many useful functions and modules in various subjects.

Usefulpy Check out the Usefulpy site Usefulpy site is not always up to date Download and Import download and install with with pip download usefulpyth

Austin Garcia 1 Dec 28, 2021
Run `black` on python code blocks in documentation files

blacken-docs Run black on python code blocks in documentation files. install pip install blacken-docs usage blacken-docs provides a single executable

Anthony Sottile 460 Dec 23, 2022
VSCode extension that generates docstrings for python files

VSCode Python Docstring Generator Visual Studio Code extension to quickly generate docstrings for python functions. Features Quickly generate a docstr

Nils Werner 506 Jan 3, 2023
A python package to import files from an adjacent folder

EasyImports About EasyImports is a python package that allows users to easily access and import files from sister folders: f.ex: - Project - Folde

null 1 Jun 22, 2022
Loudchecker - Python script to check files for earrape

loudchecker python script to check files for earrape automatically installs depe

null 1 Jan 22, 2022
An MkDocs plugin to export content pages as PDF files

MkDocs PDF Export Plugin An MkDocs plugin to export content pages as PDF files The pdf-export plugin will export all markdown pages in your MkDocs rep

Terry Zhao 266 Dec 13, 2022
sphinx builder that outputs markdown files.

sphinx-markdown-builder sphinx builder that outputs markdown files Please ★ this repo if you found it useful ★ ★ ★ If you want frontmatter support ple

Clay Risser 144 Jan 6, 2023
Zero configuration Airflow plugin that let you manage your DAG files.

simple-dag-editor SimpleDagEditor is a zero configuration plugin for Apache Airflow. It provides a file managing interface that points to your dag_fol

null 30 Jul 20, 2022
In this Github repository I will share my freqtrade files with you. I want to help people with this repository who don't know Freqtrade so much yet.

My Freqtrade stuff In this Github repository I will share my freqtrade files with you. I want to help people with this repository who don't know Freqt

Simon Kebekus 104 Dec 31, 2022
Parser manager for parsing DOC, DOCX, PDF or HTML files

Parser manager Description Parser gets PDF, DOC, DOCX or HTML file via API and saves parsed data to the database. Implemented in Ruby 3.0.1 using Acti

Эдем 4 Dec 4, 2021
epub2sphinx is a tool to convert epub files to ReST for Sphinx

epub2sphinx epub2sphinx is a tool to convert epub files to ReST for Sphinx. It uses Pandoc for converting HTML data inside epub files into ReST. It cr

Nihaal 8 Dec 15, 2022
This program has been coded to allow the user to rename all the files in the entered folder.

Bulk_File_Renamer This program has been coded to allow the user to rename all the files in the entered folder. The only required package is "termcolor

null 1 Jan 6, 2022
Read write method - Read files in various types of formats

一个关于所有格式文件读取的方法 1。 问题描述: 各种各样的文件格式,读写操作非常的麻烦,能够有一种方法,可以整合所有格式的文件,方便用户进行读取和写入。 2

null 2 Jan 26, 2022
Compare two CSV files for differences. Colorize the differences and align the columns.

pretty-csv-diff Compare two CSV files for differences. Colorize the differences and align the columns. Command-Line Example Command-Line Usage usage:

Devon 6 Dec 29, 2022
Make posters from Markdown files.

MkPosters Create posters using Markdown. Supports icons, admonitions, and LaTeX mathematics. At the moment it is restricted to the specific layout of

Patrick Kidger 243 Dec 20, 2022
A collection of simple python mini projects to enhance your python skills

A collection of simple python mini projects to enhance your python skills

PYTHON WORLD 12.1k Jan 5, 2023
Python Eacc is a minimalist but flexible Lexer/Parser tool in Python.

Python Eacc is a parsing tool it implements a flexible lexer and a straightforward approach to analyze documents.

Iury de oliveira gomes figueiredo 60 Nov 16, 2022