Python XlsxWriter – Useful Resources

Python XlsxWriter – Useful Resources ”; Previous Next The following resources contain additional information on Python XlsxWriter. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Python and Elixir Programming Bundle Course 81 Lectures 9.5 hours Pranjal Srivastava More Detail TKinter Course – Build Python GUI Apps 49 Lectures 4 hours John Elder More Detail A Beginner”s Guide to Python and Data Science 81 Lectures 8.5 hours Datai Team Academy More Detail Deploy Face Recognition Project With Python, Django, And Machine Learning Best Seller 93 Lectures 6.5 hours Srikanth Guskra More Detail Professional Python Web Development with Flask 80 Lectures 12 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;

Python XlsxWriter – Freeze & Split Panes

Python XlsxWriter – Freeze & Split Panes ”; Previous Next The freeze_panes() method The freeze_panes() method of Worksheet object in XlsxWriter library divides or splits the worksheet into horizontal or vertical regions known as panes, and “freezes” either or both of these panes so that if we scroll down or scroll down or scroll towards right, the panes (top or left respectively) remains stationary. The method requires the parameters row and col to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. You can set one of the row and col parameters as zero if you do not want either a vertical or horizontal split. Example The worksheet in the following example displays incrementing multiples of the column number in each row, so that each cell displays product of row number and column number. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() format1=wb.add_format({”bg_color”:”#D9D9D9”, ”bold”:True}) for col in range(0, 15): worksheet.write(0, col, col+1, format1) for row in range(1, 51): for col in range(0,15): if col==0: worksheet.write(row,col,(col+1)*(row + 1), format1) else: worksheet.write(row,col,(col+1)*(row + 1)) # Freeze pane on the top row. worksheet.freeze_panes(1, 0) wb.close() Output We then freeze the top row pane. As a result, after opening the worksheet, if the cell pointer is scrolled down, the top row always remains on the worksheet. Similarly, we can make the first column stationery. # Freeze pane on the first column. worksheet.freeze_panes(0, 1) The following screenshot shows that column A remains visible even if we scroll towards the right. By setting row and column parameter in freeze_panes() method to 1, both the top row and leftmost column will freeze. # Freeze pane on the first row, first column. worksheet.freeze_panes(1, 1) Open the resulting worksheet and scroll the cell cursor around. You will find that row and column numbers in top row and leftmost column, which have been formatted in bold and with a background color, are visible always. The split_panes() method The split_panes() method also divides the worksheet into horizontal or vertical regions known as panes, but unlike freeze_panes() method, the splits between the panes will be visible to the user and each pane will have its own scroll bars. The method has the parameters “y” and “x” that are used to specify the vertical and horizontal position of the split. These parameters are in terms of row height and column width used by Excel. The row heights and column widths have default values as 15 for a row and 8.43 for a column. You can set one of the “y” and “x” parameters as zero if you do not want either a vertical or horizontal split. To create a split at the 10th row and 7th column, the split_panes() method is used as follows − worksheet.split_panes(15*10, 8.43*7) You will find the splitters at 10th row and 7th column of the worksheet. You can scroll the panes to the left and right of vertical splitter and to the top and bottom of horizontal splitter. Note that the other panes will remain constant. Example Here”s the complete code that creates the splitter, and below that the output is shown − import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() format1=wb.add_format({”bg_color”:”#D9D9D9”, ”bold”:True}) for col in range(0, 15): worksheet.write(0, col, col+1, format1) for row in range(1, 51): for col in range(0,15): if col==0: worksheet.write(row,col,(col+1)*(row + 1), format1) else: worksheet.write(row,col,(col+1)*(row + 1)) worksheet.split_panes(15*10, 8.43*7) wb.close() Output Run the code and open hello.xlsx using Excel. As we can see, the worksheet is split into different panes at 10th row and 7th column. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Page Setup

Python XlsxWriter – Page Setup ”; Previous Next The worksheet page setup methods are related to appearance of the worksheet when it is printed. These worksheet methods control the orientation, paper size, margins, etc. set_landscape() This method is used to set the orientation of a worksheet”s printed page to landscape. set_portrait() This method is used to set the orientation of a worksheet”s printed page to portrait. This is the default orientation. set_page_view() This method is used to display the worksheet in “Page View/Layout” mode. set_paper() This method is used to set the paper format for the printed output of a worksheet. It takes index as an integer argument. It is the Excel paper format index. Following are some of the paper styles and index values − Index Paper format Paper size 0 Printer default Printer default 1 Letter 8 1/2 x 11 in 2 Letter Small 8 1/2 x 11 in 3 Tabloid 11 x 17 in 4 Ledger 17 x 11 in 5 Legal 8 1/2 x 14 in 6 Statement 5 1/2 x 8 1/2 in 7 Executive 7 1/4 x 10 1/2 in 8 A3 297 x 420 mm 9 A4 210 x 297 mm set_margin() This method is used to set the margins of the worksheet when it is printed. It accepts left, right, top and bottom parameters whose values are in inches. All parameters are optional The left and right parameters are 0.7 by default, and top and bottom are 0.75 by default. Print Page Previous Next Advertisements ”;

Python XlsxWriter – VBA Macro

Python XlsxWriter – VBA Macro ”; Previous Next In Excel, a macro is a recorded series of steps that can be repeated any number of times with a shortcut key. The steps performed while recording the macro are translated into programming instructions VBA which stands for Visual Basic for Applications. VBA is a subset of Visual basic language, especially written to automate the tasks in MS Office apps such as Word, Excel, PowerPoint etc. The option to record a macro is available in the Developer menu of MS Excel. If this menu is not seen, it has to be activated by going to the “File→Options→Customize” ribbon screen. As shown in the following figure, click the Record Macro button by going to “View→Macros→Record Macro”, and give a suitable name to the macro and perform desired actions to be recorded. After the steps are over stop the recording. Assign a desired shortcut so that the recorded action can be repeated as and it is pressed. To view the VBA code, edit the macro by going View→ZMacros→View Macros. Select the Macro from Macro name and click on Edit. The VBA editor will be shown. Delete all the steps generated by Excel and add the statement to pop-up a message box. Confirm that the macro works perfectly. Press CTL+Shift+M and the message box pops up. Save this file with the .xlsm extension. It internally contains vbaproject.bin, a binary OLE COM container. To extract it from the Excel macro file, use the vba_extract.py utility. (xlsxenv) E:xlsxenv>vba_extract.py test.xlsm Extracted: vbaProject.bin Example This vbaProject.bin file can now be added to the XlsxWriter workbook using the add_vba_project() method. On this worksheet, place a button object at B3 cell, and link it to the macro that we had already created (i.e., macro1) import xlsxwriter workbook = xlsxwriter.Workbook(”testvba.xlsm”) worksheet = workbook.add_worksheet() worksheet.set_column(”A:A”, 30) workbook.add_vba_project(”./vbaProject.bin”) worksheet.write(”A3”, ”Press the button to say Welcome.”) worksheet.insert_button( ”B3”, { ”macro”: ”macro1”, ”caption”: ”Press Me”, ”width”: 80, ”height”: 30 } ) workbook.close() Output When the above code is executed, the macro enabled workbook named testvba.xlsm will be created. Open it and click on the button. It will cause the message box to pop up as shown. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Border

Python XlsxWriter – Border ”; Previous Next This section describes how to apply and format the appearance of cell border as well as a border around text box. Working with Cell Border The properties in the add_format() method that control the appearance of cell border are as shown in the following table − Description Property method Cell border ”border” set_border() Bottom border ”bottom” set_bottom() Top border ”top” set_top() Left border ”left” set_left() Right border ”right” set_right() Border color ”border_color” set_border_color() Bottom color ”bottom_color” set_bottom_color() Top color ”top_color” set_top_color() Left color ”left_color” set_left_color() Right color ”right_color” set_right_color() Note that for each property of add_format() method, there is a corresponding format class method starting with the set_propertyname() method. For example, to set a border around a cell, we can use border property in add_format() method as follows − f1= wb.add_format({ ”border”:2}) The same action can also be done by calling the set_border() method − f1 = workbook.add_format() f1.set_border(2) Individual border elements can be configured by the properties or format methods as follows − set_bottom() set_top() set_left() set_right() These border methods/properties have an integer value corresponding to the predefined styles as in the following table − Index Name Weight Style 0 None 0 1 Continuous 1 ———– 2 Continuous 2 ———– 3 Dash 1 – – – – – – 4 Dot 1 . . . . . . 5 Continuous 3 ———– 6 Double 3 =========== 7 Continuous 0 ———– 8 Dash 2 – – – – – – 9 Dash Dot 1 – . – . – . 10 Dash Dot 2 – . – . – . 11 Dash Dot Dot 1 – . . – . . 12 Dash Dot Dot 2 – . . – . . 13 SlantDash Dot 2 / – . / – . Example Following code shows how the border property is used. Here, each row is having a border style 2 corresponding to continuous bold. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() f1=wb.add_format({”bold”:True, ”border”:2, ”border_color”:”red”}) f2=wb.add_format({”border”:2, ”border_color”:”red”}) headings = [”Month”, ”Product A”, ”Product B”] data = [ [”Jan”, ”Feb”, ”Mar”, ”Apr”, ”May”, ”June”], [10, 40, 50, 20, 10, 50], [30, 60, 70, 50, 40, 30], ] ws.write_row(”A1”, headings, f1) ws.write_column(”A2”, data[0], f2) ws.write_column(”B2”, data[1],f2) ws.write_column(”C2”, data[2],f2) wb.close() Output The worksheet shows a bold border around the cells. Working with Textbox Border The border property is also available for the text box object. The text box also has a line property which is similar to border, so that they can be used interchangeably. The border itself can further be formatted by none, color, width and dash_type parameters. Line or border set to none means that the text box will not have any border. The dash_type parameter can be any of the following values − solid round_dot square_dot dash dash_dot long_dash long_dash_dot long_dash_dot_dot Example Here is a program that displays two text boxes, one with a solid border, red in color; and the second box has dash_dot type border in blue color. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() ws.insert_textbox(”B2”, ”Welcome to Tutorialspoint”, {”border”: {”color”: ”#FF9900”}}) ws.insert_textbox(”B10”, ”Welcome to Tutorialspoint”, { ”line”: {”color”: ”blue”, ”dash_type”: ”dash_dot”} }) wb.close() Output The output worksheet shows the textbox borders. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Working with Pandas

Python XlsxWriter – Working with Pandas ”; Previous Next Pandas is a popular Python library for data manipulation and analysis. We can use XlsWriter for writing Pandas dataframes into an Excel worksheet. To learn the features described in this section, we need to install Pandas library in the same environment in which XlsxWriter has been installed. pip3 install pandas Using XlsxWriter with Pandas Let us start with a simple example. First, create a Pandas dataframe from the data from a list of integers. Then use XlsxWriter as the engine to create a Pandas Excel writer. With the help of this engine object, we can write the dataframe object to Excel worksheet. Example import pandas as pd df = pd.DataFrame({”Data”: [10, 20, 30, 20, 15, 30, 45]}) writer = pd.ExcelWriter(”hello.xlsx”, engine=”xlsxwriter”) df.to_excel(writer, sheet_name=”Sheet1”) writer.save() Output The worksheet so created shows up as follows − Adding Charts to Pandas Dataframe Just as we obtain an object of Workbook class, and then a Worksheet object by calling its add_worksheet() method, the writer object can also be used to fetch these objects. Once we get them, the XlsxWriter methods to add chart, data table etc. can be employed. In this example, we set up a Pandas dataframe and obtain its dimension (or shape). import pandas as pd df = pd.DataFrame({”Data”: [105, 60, 35, 90, 15, 30, 75]}) writer = pd.ExcelWriter(”hello.xlsx”, engine=”xlsxwriter”) df.to_excel(writer, sheet_name=”Sheet1”) (max_row, max_col) = df.shape The workbook and worksheet objects are created from the writer. workbook = writer.book worksheet = writer.sheets[”Sheet1”] Rest of things are easy. The chart object is added as we have done earlier. chart = workbook.add_chart({”type”: ”column”}) chart.add_series({”values”: [”Sheet1”, 1, 1, max_row, 1]}) worksheet.insert_chart(1, 3, chart) writer.save() Example The following code uses Pandas dataframe to write an Excel workbook and a column chart is prepared by XlsxWriter. import pandas as pd df = pd.DataFrame({”Data”: [105, 60, 35, 90, 15, 30, 75]}) writer = pd.ExcelWriter(”hello.xlsx”, engine=”xlsxwriter”) df.to_excel(writer, sheet_name=”Sheet1”) (max_row, max_col) = df.shape workbook = writer.book worksheet = writer.sheets[”Sheet1”] chart = workbook.add_chart({”type”: ”column”}) chart.add_series({”values”: [”Sheet1”, 1, 1, max_row, 1]}) worksheet.insert_chart(1, 3, chart) writer.save() Output The column chart along with the data is shown below − Writing Dataframe to Excel Table Similarly, the dataframe can be written to Excel table object. The dataframe here is derived from a Python dictionary, where the keys are dataframe column headers. Each key has list as a value which in turn becomes values of each column. import pandas as pd df = pd.DataFrame({ ”Name”: [”Namrata”,”Ravi”,”Kiran”,”Karishma”], ”Percent”: [73.33, 70, 75, 65.5], ”RollNo”: [1, 2,3,4]}) df = df[[”RollNo”, ”Name”, ”Percent”]] (max_row, max_col) = df.shape Use xlsxwriter engine to write the dataframe to a worksheet (sheet1) writer = pd.ExcelWriter(”hello.xlsx”, engine=”xlsxwriter”) df.to_excel(writer, sheet_name=”Sheet1”, startrow=1, header=False, index=False) Following lines give Workbook and Worksheet objects. workbook = writer.book worksheet = writer.sheets[”Sheet1”] Data in the worksheet is converted to Table with the help of add_table() method. column_settings = [{”header”: column} for column in df.columns] worksheet.add_table(0, 0, max_row, max_col – 1, {”columns”: column_settings}) writer.save() Example Below is the complete code to write pandas dataframe to Excel table. import pandas as pd df = pd.DataFrame({ ”Name”: [”Namrata”,”Ravi”,”Kiran”,”Karishma”], ”Percent”: [73.33, 70, 75, 65.5], ”RollNo”: [1, 2,3,4] }) df = df[[”RollNo”, ”Name”, ”Percent”]] (max_row, max_col) = df.shape writer = pd.ExcelWriter(”hello.xlsx”, engine=”xlsxwriter”) df.to_excel(writer, sheet_name=”Sheet1”, startrow=1, header=False, index=False) workbook = writer.book worksheet = writer.sheets[”Sheet1”] column_settings = [{”header”: column} for column in df.columns] worksheet.add_table(0, 0, max_row, max_col – 1, {”columns”: column_settings}) writer.save() Output The Table using default autofilter settings appears at A1 cell onwards. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Chart Legends

Python XlsxWriter – Chart Legends ”; Previous Next Depending upon the type of chart, the data is visually represented in the form of columns, bars, lines, arcs, etc. in different colors or patterns. The chart legend makes it easy to quickly understand which color/pattern corresponds to which data series. Working with Chart Legends To set the legend and configure its properties such as position and font, XlsxWriter has set_legend() method. The properties are − None − In Excel chart legends are on by default. The none=True option turns off the chart legend. Position − Set the position of the chart legend. It can be set to top, bottom, left, right, none. Font − Set the font properties (like name, size, bold, italic etc.) of the chart legend. Border − Set the border properties of the legend such as color and style. Fill − Set the solid fill properties of the legend such as color. Pattern − Set the pattern fill properties of the legend. Gradient − Set the gradient fill properties of the legend. Some of the legend properties are set for the chart as below − chart1.set_legend( {”position”:”bottom”, ”font”: {”name”:”calibri”,”size”: 9, ”bold”: True}} ) Example Here is the complete code to display legends as per the above characteristics − import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() chart1 = wb.add_chart({”type”: ”column”}) # Add the worksheet data that the charts will refer to. headings = [”Name”, ”Phy”, ”Maths”] data = [ [“Jay”, 30, 60], [“Mohan”, 40, 50], [“Veeru”, 60, 70], ] worksheet.write_row(0,0, headings) worksheet.write_row(1,0, data[0]) worksheet.write_row(2,0, data[1]) worksheet.write_row(3,0, data[2]) chart1.add_series({ ”name”: ”=Sheet1!$B$1”, ”categories”: ”=Sheet1!$A$2:$A$4”, ”values”: ”=Sheet1!$B$2:$B$4”, }) chart1.add_series({ ”name”: [”Sheet1”, 0, 2], ”categories”: [”Sheet1”, 1, 0, 3, 0], ”values”: [”Sheet1”, 1, 2, 3, 2], }) chart1.set_title ({”name”: ”Marklist”, ”name_font”: {”name”:”Times New Roman”, ”size”:24}}) chart1.set_x_axis({”name”: ”Students”, ”name_font”: {”name”:”Arial”, ”size”:16, ”bold”:True},}) chart1.set_y_axis({”name”: ”Marks”,”name_font”: {”name”:”Arial”, ”size”:16, ”bold”:True}, ”num_font”:{”name”:”Arial”, ”italic”:True}}) chart1.set_legend({”position”:”bottom”, ”font”: {”name”:”calibri”,”size”: 9, ”bold”: True}}) worksheet.insert_chart(”B7”, chart1) wb.close() Output The chart shows the legend below the caption of the X axis. In the chart, the columns corresponding to physics and maths are shown in different colors. The small colored box symbols to the right of the chart are the legends that show which color corresponds to physics or maths. Print Page Previous Next Advertisements ”;

Python XlsxWriter – Data Validation

Python XlsxWriter – Data Validation ”; Previous Next Data validation feature in Excel allows you to control what a user can enter into a cell. You can use it to ensure that the value in a cell is a number/date within a specified range, text with required length, or to present a dropdown menu to choose the value from. The data validation tools are available in the Data menu. The first tab allows you to set a validation criterion. Following figure shows that criteria requires the cell should contain an integer between 1 to 25 − In the second tab, set the message to be flashed when user”s cursor is on the desired cell, which in this case is ”Enter any integer between 1 to 25”. You can also set the message title; in this case it is Age. The third tab allows asks you to define any error message you would like to flash if the validation criteria fails. When the user places the cursor in I10 (for which the validation is set), you can see the input message. When the entered number is not in the range, the error message will flash. Working with XlsxWriter Data Validation You can set the validation criteria, input and error message programmatically with data_validation() method. worksheet.data_validation( ”I10”, { ”validate”: ”integer”,”criteria”: ”between”, ”minimum”: 1,”maximum”: 25, ”input_title”: ”Enter an integer:”, ”input_message”: ”between 1 and 25”, ”error_title”: ”Input value is not valid!”, ”error_message”: ”It should be an integer between 1 and 25” } ) The data_validation() method accepts options parameter as a dictionary with following parameters − validate − It is used to set the type of data that you wish to validate. Allowed values are integer, decimal, list, date, time, length etc. criteria − It is used to set the criteria for validation. It can be set to any logical operator including between/ not between, ==, !=, <, >, <=, >=, etc. value − Sets the limiting value to which the criteria is applied. It is always required. When using the list validation, it is given as a Comma Separated Variable string. input_title − Used to set the title of the input message when the cursor is placed in the target cell. input_message − The message to be displayed when a cell is entered. error_title − The title of the error message to be displayed when validation criteria is not met. error_message − Sets the error message. The default error message is “The value you entered is not valid. A user has restricted values that can be entered into the cell.” Example Following usage of data_validation() method results in the behavior of data validation feature as shown in the above figures. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() worksheet.data_validation( ”I10”, { ”validate”: ”integer”,”criteria”: ”between”, ”minimum”: 1,”maximum”: 25, ”input_title”: ”Enter an integer:”, ”input_message”: ”between 1 and 25”, ”error_title”: ”Input value is not valid!”, ”error_message”:”It should be an integer between 1 and 25” } ) wb.close() As another example, the cell I10 is set a validation criterion so as to force the user choose its value from a list of strings in a drop down. worksheet.data_validation( ”I10”, { ”validate”: ”list”, ”source”: [”Mumbai”, ”Delhi”, ”Chennai”, ”Kolkata”], ”input_title”: ”Choose one:”, ”input_message”: ”Select a value from th list”, } ) Example The modified program for validation with the drop down list is as follows − import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() worksheet.data_validation( ”I10”, { ”validate”: ”list”, ”source”: [”Mumbai”, ”Delhi”, ”Chennai”, ”Kolkata”], ”input_title”: ”Choose one:”, ”input_message”: ”Select a value from the list”, } ) wb.close() Output The dropdown list appears when the cursor is placed in I10 cell − Example If you want to make the user enter a string of length greater than 5, use >= as criteria and value set to 5. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() worksheet.data_validation( ”I10”,{ ”validate”: ”length”, ”criteria”: ”>=”,”value”: 5,”input_title”: ”Enter name:”, ”input_message”: ”Minimum length 5 character”, ”error_message”:”Name should have at least 5 characters” } ) wb.close() Output If the string is having less than 5 characters, the error message pops up as follows − Print Page Previous Next Advertisements ”;

Python XlsxWriter – Chart Formatting

Python XlsxWriter – Chart Formatting ”; Previous Next The default appearance of chart can be customized to make it more appealing, explanatory and user friendly. With XlsxWriter, we can do following enhancements to a Chart object − Set and format chart title Set the X and Y axis titles and other parameters Configure the chart legends Chat layout options Setting borders and patterns Title You can set and configure the main title of a chart object by calling its set_title() method. Various parameters that can be are as follows − Name − Set the name (title) for the chart to be displayed above the chart. The name property is optional. The default is to have no chart title. name_font − Set the font properties for the chart title. Overlay − Allow the title to be overlaid on the chart. Layout − Set the (x, y) position of the title in chart relative units. None − Excel adds an automatic chart title. The none option turns this default title off. It also turns off all other set_title() options. X and Y axis The two methods set_x_axis() and set_y_axis() are used to axis titles, the name_font to be used for the title text, the num_font to be used for numbers displayed on the X and Y axis. name − Set the title or caption for the axis. name_font − Set the font properties for the axis title. num_font − Set the font properties for the axis numbers. num_format − Set the number format for the axis. major_gridlines − Configure the major gridlines for the axis. display_units − Set the display units for the axis. In the previous example, where the data of marklist has been shown in the form of a column chart, we set up the chart formatting options such as the chart title and X as well as Y axis captions and their other display properties as follows − chart1.set_x_axis( {”name”: ”Students”, ”name_font”:{”name”:”Arial”, ”size”:16, ”bold”:True},}) chart1.set_y_axis( { ”name”: ”Marks”, ”name_font”: {”name”:”Arial”, ”size”:16, ”bold”:True}, ”num_font”:{”name”:”Arial”, ”italic”:True} } ) Example Add the above snippet in the complete code. It now looks as given below − import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) worksheet = wb.add_worksheet() chart1 = wb.add_chart({”type”: ”column”}) # Add the worksheet data that the charts will refer to. headings = [”Name”, ”Phy”, ”Maths”] data = [ [“Jay”, 30, 60], [“Mohan”, 40, 50], [“Veeru”, 60, 70], ] worksheet.write_row(0,0, headings) worksheet.write_row(1,0, data[0]) worksheet.write_row(2,0, data[1]) worksheet.write_row(3,0, data[2]) chart1.add_series({ ”name”: ”=Sheet1!$B$1”, ”categories”: ”=Sheet1!$A$2:$A$4”, ”values”: ”=Sheet1!$B$2:$B$4”, }) chart1.add_series({ ”name”: [”Sheet1”, 0, 2], ”categories”: [”Sheet1”, 1, 0, 3, 0], ”values”: [”Sheet1”, 1, 2, 3, 2], }) chart1.set_title ({”name”: ”Marklist”, ”name_font”: {”name”:”Times New Roman”, ”size”:24} }) chart1.set_x_axis({”name”: ”Students”, ”name_font”: {”name”:”Arial”, ”size”:16, ”bold”:True}, }) chart1.set_y_axis({”name”: ”Marks”, ”name_font”:{”name”:”Arial”, ”size”:16, ”bold”:True}, ”num_font”:{”name”:”Arial”, ”italic”:True} }) worksheet.insert_chart(”B7”, chart1) wb.close() Output The chart shows the title and axes captions as follows − Print Page Previous Next Advertisements ”;

Python XlsxWriter – Sparklines

Python XlsxWriter – Sparklines ”; Previous Next A sparkline is a small chart, that doesn”t have axes or coordinates. It gives a representation of variation of a certain parameter. Normal charts are bigger in size, with a lot of explanatory features such as title, legend, data labels etc. and are set off from the accompanying text. Sparkline on the other hand is small in size and can be embedded inside the text, or a worksheet cell that has its context. Feature of Sparkline was introduced by Edward Tufte in 1983. Microsoft introduced sparklines in Excel 2010. We can find sparkline option in the insert ribbon of Excel software. Sparklines are of three types − line − Similar to line chart column − Similar to column chart win_loss − Whether each value is positive (win) or negative (loss). Working with XlsxWriter Sparklines XlsxWriter module has add_sparkline() method. It basically needs the cell location of the sparkline and the data range to be represented as a sparkline. Optionally, other parameters such as type, style, etc. are provided in the form of dictionary object. By default, the type is line. Example Following program represents same list of numbers in line and column sparklines. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() data=[12,23,9,17,31,3,7,21,10,15] ws.write_row(”A1”, data) ws.set_column(”K:K”, 40) ws.set_row(0, 30) ws.add_sparkline(”K1”, {”range”:”Sheet1!A1:J1”}) ws.write_row(”A5”, data) ws.set_column(”K:K”, 40) ws.set_row(4, 30) ws.add_sparkline(”K5”, {”range”:”Sheet1!A5:J5”, ”type”:”column”}) wb.close() Output In cell K, the sparklines are added. The properties are − range − is the mandatory parameter. It specifies the cell data range that the sparkline will plot. type − specifies the type of sparkline. There are 3 available sparkline types are line, column and win_loss. markers − Turn on the markers for line style sparklines style − The sparkline styles defined in MS Excel. There are 36 style types. negative_points − If set to True, the negative points in a sparkline are highlighted. Example The following program produces a line sparkline with markers and a win_loss sparkline having negative points highlighted. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() data=[12,23,9,17,31,3,7,21,10,15] ws.write_row(”A1”, data) ws.set_column(”K:K”, 40) ws.set_row(0, 30) data=[1,1,-1,-1,-1,1,1,1,-1,-1] ws.write_row(”A5”, data) ws.set_column(”K:K”, 40) ws.set_row(4, 30) ws.add_sparkline(”K1”, {”range”:”Sheet1!A1:J1”, ”markers”:True}) ws.add_sparkline(”K5”, {”range”:”Sheet1!A5:J5”, ”type”:”win_loss”, ”negative_points”:True}) wb.close() Output Line Sparkline in K1 has markers. The sparkline in K5 shows negative points highlighting. Example – Style Types Following code displays a series of numbers in column sparkline. Ten different style types are used here. import xlsxwriter wb = xlsxwriter.Workbook(”hello.xlsx”) ws = wb.add_worksheet() data=[12,23,9,17,31,3,7,21,10,15] ws.write_row(”C3”, data) ws.set_column(”B:B”,40) for i in range(1,11): ws.write(i+4,0, ”style {}”.format(i)) ws.add_sparkline(i+4,1, {”range”:”Sheet1!$C$3:$L$3”, ”type”:”column”, ”style”:i}) wb.close() Output It will produce the following output − Print Page Previous Next Advertisements ”;