Python XlsxWriter – Important classes

Python XlsxWriter – Important Classes ”; Previous Next The XlsxWriter library comprises of following classes. All the methods defined in these classes allow different operations to be done programmatically on the XLSX file. The classes are − Workbook class Worksheet class Format class Chart class Chartsheet class Exception class Workbook Class This is the main class exposed by the XlsxWriter module and it is the only class that you will need to instantiate directly. It represents the Excel file as it is written on a disk. wb=xlsxwriter.Workbook(”filename.xlsx”) The Workbook class defines the following methods − Sr.No Workbook Class & Description 1 add_worksheet() Adds a new worksheet to a workbook. 2 add_format() Used to create new Format objects which are used to apply formatting to a cell. 3 add_chart() Creates a new chart object that can be inserted into a worksheet via the insert_chart() Worksheet method 4 add_chartsheet() Adds a new chartsheet to a workbook. 5 close() Closes the Workbook object and write the XLSX file. 6 define_name() Creates a defined name in the workbook to use as a variable. 7 add_vba_project() Used to add macros or functions to a workbook using a binary VBA project file. 8 worksheets() Returns a list of the worksheets in a workbook. Worksheet Class The worksheet class represents an Excel worksheet. An object of this class handles operations such as writing data to cells or formatting worksheet layout. It is created by calling the add_worksheet() method from a Workbook() object. The Worksheet object has access to the following methods − write() Writes generic data to a worksheet cell. Parameters − row − The cell row (zero indexed). col − The cell column (zero indexed). *args − The additional args passed to the sub methods such as number, string and cell_format. Returns − 0 − Success -1 − Row or column is out of worksheet bounds. write_string() Writes a string to the cell specified by row and column. Parameters − row (int) − The cell row (zero indexed). col (int) − The cell column (zero indexed). string (string) − String to write to cell. cell_format (Format) − Optional Format object. Returns − 0 − Success -1 − Row or column is out of worksheet bounds. -2 − String truncated to 32k characters. write_number() Writes numeric types to the cell specified by row and column. Parameters − row (int) − The cell row (zero indexed). col (int) − The cell column (zero indexed). string (string) − String to write to cell. cell_format (Format) − Optional Format object. Returns − 0 − Success -1 − Row or column is out of worksheet bounds. write_formula() Writes a formula or function to the cell specified by row and column. Parameters − row (int) − The cell row (zero indexed). col (int) − The cell column (zero indexed). formula (string) −Formula to write to cell. cell_format (Format) − Optional Format object. value − Optional result. The value if the formula was calculated. Returns − 0 − Success -1 − Row or column is out of worksheet bounds. insert_image() Used to insert an image into a worksheet. The image can be in PNG, JPEG, GIF, BMP, WMF or EMF format. Parameters − row (int) − The cell row (zero indexed). col (int) − The cell column (zero indexed). filename − Image filename (with path if required). Returns − 0 − Success -1 − Row or column is out of worksheet bounds. insert_chart() Used to insert a chart into a worksheet. A chart object is created via the Workbook add_chart() method. Parameters − row (int) − The cell row (zero indexed). col (int) − The cell column (zero indexed). chart − A chart object. conditional_format() Used to add formatting to a cell or range of cells based on user-defined criteria. Parameters − first_row (int) − The first row of the range.(All zero indexed) first_col (int) − The first column of the range. last_row (int) − The last row of the range. last_col (int)− The last col of the range. options (dict) − Conditional formatting options. must be a dictionary containing the parameters that describe the type and style of the conditional format Returns − 0 − Success -1 − Row or column is out of worksheet bounds. -2 − Incorrect parameter or option. add_table() Used to group a range of cells into an Excel Table. Parameters − first_row (int) − The first row of the range. (All zero indexed) first_col (int) − The first column of the range. last_row (int) − The last row of the range. last_col (int) − The last col of the range. options (dict) − Table formatting options. autofilter() Set the auto-filter area in the worksheet. It adds drop down lists to the headers of a 2D range of worksheet data. User can filter the data based on simple criteria. Parameters

Python XlsxWriter – Defined Names

Python XlsxWriter – Defined Names ”; Previous Next In Excel, it is possible to identify a cell, a formula, or a range of cells by user-defined name, which can be used as a variable used to make the definition of formula easy to understand. This can be achieved using the define_name() method of the Workbook class. In the following code snippet, we have a range of cells consisting of numbers. This range has been given a name as marks. data=[”marks”,50,60,70, ”Total”] ws.write_row(”A1”, data) wb.define_name(”marks”, ”=Sheet1!$A$1:$E$1”) If the name is assigned to a range of cells, the second argument of define_name() method is a string with the name of the sheet followed by “!” symbol and then the range of cells using the absolute addressing scheme. In this case, the range A1:E1 in sheet1 is named as marks. This name can be used in any formula. For example, we calculate the sum of numbers in the range identified by the name marks. ws.write(”F1”, ”=sum(marks)”) We can also use the named cell in the write_formula() method. In the following code, this method is used to calculate interest on the amount where the rate is a defined_name. ws.write(”B5”, 10) wb.define_name(”rate”, ”=sheet1!$B$5”) ws.write_row(”A5”, [”Rate”, 10]) data=[”Amount”,1000, 2000, 3000] ws.write_column(”A6”, data) ws.write(”B6”, ”Interest”) for row in range(6,9): ws.write_formula(row, 1, ”= rate*$A{}/100”.format(row+1)) We can also use write_array_formula() method instead of the loop in the above code − ws.write_array_formula(”D7:D9” , ”{=rate/100*(A7:A9)}”) Example The complete code using define_name() method is given below − import xlsxwriter wb = xlsxwriter.Workbook(”ex2.xlsx”) ws = wb.add_worksheet() data = [”marks”,50,60,70, ”Total”] ws.write_row(”A1”, data) wb.define_name(”marks”, ”=Sheet1!$A$1:$E$1”) ws.write(”F1”, ”=sum(marks)”) ws.write(”B5”, 10) wb.define_name(”rate”, ”=sheet1!$B$5”) ws.write_row(”A5”, [”Rate”, 10]) data=[”Amount”,1000, 2000, 3000] ws.write_column(”A6”, data) ws.write(”B6”, ”Interest”) for row in range(6,9): ws.write_formula(row, 1, ”= rate*$A{}/100”.format(row+1)) wb.close() Output Run the above program and open ex2.xlsx with Excel. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Overview

Python XlsxWriter – Overview ”; Previous Next XlsxWriter is a Python module for creating spreadsheet files in Excel 2007 (XLSX) format that uses open XML standards. XlsxWriter module has been developed by John McNamara. Its earliest version (0.0.1) was released in 2013. The latest version 3.0.2 was released in November 2021. The latest version requires Python 3.4 or above. XlsxWriter Features Some of the important features of XlsxWriter include − Files created by XlsxWriter are 100% compatible with Excel XLSX files. XlsxWriter provides full formatting features such as Merged cells, Defined names, conditional formatting, etc. XlsxWriter allows programmatically inserting charts in XLSX files. Autofilters can be set using XlsxWriter. XlsxWriter supports Data validation and drop-down lists. Using XlsxWriter, it is possible to insert PNG/JPEG/GIF/BMP/WMF/EMF images. With XlsxWriter, Excel spreadsheet can be integrated with Pandas library. XlsxWriter also provides support for adding Macros. XlsxWriter has a Memory optimization mode for writing large files. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Environment Setup

Python XlsxWriter – Environment Setup ”; Previous Next Installing XlsxWriter using PIP The easiest and recommended method of installing XlsxWriter is to use PIP installer. Use the following command to install XlsxWriter (preferably in a virtual environment). pip3 install xlsxwriter Installing from a Tarball Another option is to install XlsxWriter from its source code, hosted at https://github.com/jmcnamara/XlsxWriter/. Download the latest source tarball and install the library using the following commands − $ curl -O -L http://github.com/jmcnamara/XlsxWriter/archive/main.tar.gz $ tar zxvf main.tar.gz $ cd XlsxWriter-main/ $ python setup.py install Cloning from GitHub You may also clone the GitHub repository and install from it. $ git clone https://github.com/jmcnamara/XlsxWriter.git $ cd XlsxWriter $ python setup.py install To confirm that XlsxWriter is installed properly, check its version from the Python prompt − >>> import xlsxwriter >>> xlsxwriter.__version__ ”3.0.2” Print Page Previous Next Advertisements ”;

Python XlsxWriter – Hello World

Python XlsxWriter – Hello World ”; Previous Next Getting Started The first program to test if the module/library works correctly is often to write Hello world message. The following program creates a file with .XLSX extension. An object of the Workbook class in the xlsxwriter module corresponds to the spreadsheet file in the current working directory. wb = xlsxwriter.Workbook(”hello.xlsx”) Next, call the add_worksheet() method of the Workbook object to insert a new worksheet in it. ws = wb.add_worksheet() We can now add the Hello World string at A1 cell by invoking the write() method of the worksheet object. It needs two parameters: the cell address and the string. ws.write(”A1”, ”Hello world”) Example The complete code of hello.py is as follows − import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() ws.write(”A1”, ”Hello world”) wb.close() Output After the above code is executed, hello.xlsx file will be created in the current working directory. You can now open it using Excel software. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Home

Python XlsxWriter Tutorial PDF Version Quick Guide Resources Job Search Discussion XlsxWriter is a Python library for creating spreadsheet files in Excel 2007 (XLSX) format. This library has been developed by John McNamara. Its latest version is 3.0.2 which was released in November 2021. The latest version requires Python 3.4 or above. Audience This tutorial is meant for Python developers who are interested in programmatically automating the functionality of MS Excel software. Prerequisites Before proceeding with this tutorial, you should have an understanding of Python programming and proficiency in handling MS Excel of intermediate level. The knowledge of object oriented programming is desired but not essential. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Cell Notation & Ranges

Python XlsxWriter – Cell Notation & Ranges ”; Previous Next Each worksheet in a workbook is a grid of a large number of cells, each of which can store one piece of data – either value or formula. Each Cell in the grid is identified by its row and column number. In Excel”s standard cell addressing, columns are identified by alphabets, A, B, C, …., Z, AA, AB etc., and rows are numbered starting from 1. The address of each cell is alphanumeric, where the alphabetic part corresponds to the column and number corresponding to the row. For example, the address “C5” points to the cell in column “C” and row number “5”. Cell Notations The standard Excel uses alphanumeric sequence of column letter and 1-based row. XlsxWriter supports the standard Excel notation (A1 notation) as well as Row-column notation which uses a zero based index for both row and column. Example In the following example, a string ”Hello world” is written into A1 cell using Excel”s standard cell address, while ”Welcome to XLSXWriter” is written into cell C5 using row-column notation. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() ws.write(”A1”, ”Hello world”) # A1 notation ws.write(4,2,”Welcome to XLSXWriter”) # Row-column notation wb.close() Output Open the hello.xlsx file using Excel software. The numbered row-column notation is especially useful when referring to the cells programmatically. In the following code data in a list of lists has to be written to a range of cells in a worksheet. This is achieved by two nested loops, the outer representing the row numbers and the inner loop for column numbers. data = [ [”Name”, ”Physics”, ”Chemistry”, ”Maths”, ”Total”], [”Ravi”, 60, 70, 80], [”Kiran”, 65, 75, 85], [”Karishma”, 55, 65, 75], ] for row in range(len(data)): for col in range(len(data[row])): ws.write(row, col, data[row][col]) The same result can be achieved by using write_row() method of the worksheet object used in the code below − for row in range(len(data)): ws.write_row(6+row,0, data[row]) The worksheet object has add_table() method that writes the data to a range and converts into Excel range, displaying autofilter dropdown arrows in the top row. ws.add_table(”G6:J9”, {”data”: data, ”header_row”:True}) Example The output of all the three codes above can be verified by the following code and displayed in the following figure − import xlsxwriter wb = xlsxwriter.Workbook(”ex1.xlsx”) ws = wb.add_worksheet() data = [ [”Name”, ”Physics”, ”Chemistry”, ”Maths”, ”Total”], [”Ravi”, 60, 70, 80], [”Kiran”, 65, 75, 85], [”Karishma”, 55, 65, 75], ] for row in range(len(data)): for col in range(len(data[row])): ws.write(row, col, data[row][col]) for row in range(len(data)): ws.write_row(6+row,0, data[row]) ws.add_table(”G6:J9”, {”data”: data, ”header_row”:False}) wb.close() Output Execute the above program and open the ex1.xlsx using Excel software. Print Page Previous Next Advertisements ”;