Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)

Introduction

As a webServer APIServer, I would like to introduce Tornado, which is easy and excellent (I think), in several parts.

[Web-WF Python Tornado Part 1] (https://qiita.com/sin_hayasi/private/c5af3b21e7abda196cfd) [Web-WF Python Tornado Part 2] (https://qiita.com/sin_hayasi/private/bdc4f45b092ed5433aec) Web-WF Python Tornado Part 3 (This article

Target

Full stack engineer, front engineer, person who likes Python, person who read part 1 and part 2, person who was forced to output some material with Excel

Python3.6 or above, tornado installed

goal

This time, I will introduce a module that is convenient to have in the application with a slightly different taste. (Openpyxl)

What is Openpyxl

Module that can read, write and edit Excel files from python It is convenient to output the aggregated result as a report in Excel, or conversely to import the Excel data. This time I will create a sample to output the invoice [Official here] (https://openpyxl.readthedocs.io/en/stable/)

Installation

Openpyxl can only be installed with pip

$ pip install openpyxl

preparation of excel template

Prepare the following template (The part in red is a macro sample) スクリーンショット 2020-08-24 18.43.28.png

Source code

Add the following sources to the sources introduced in Part 1 and Part 2.

main.py


import os
import datetime
import openpyxl as px
from openpyxl.writer.excel import save_virtual_workbook

class prtInvoice(tornado.web.RequestHandler):
    def get(self):
        #Load invoice template
        wb = px.load_workbook(BASE_DIR+u'/template.xlsx')
        ws = wb.active
        #Specify print range
        ws.page_setup.fitToWidth = 1
        ws.page_setup.fitToHeight = 0
        ws.sheet_properties.pageSetUpPr.fitToPage = True
        #Prepare such a model (actually from DB etc.
        model = {
            'companyName': 'Test company',
            'items': [
                {'itemName': 'Product A', 'price': 1000, 'quantity': 1},
                {'itemName': 'Product B', 'price': 2000, 'quantity': 2},
                {'itemName': 'Product C', 'price': 3000, 'quantity': 3}
            ]
        }

        #Set today's date
        #F2 is a cell in Excel
        dt_now = datetime.datetime.now()
        ws['F2'] = dt_now.strftime("%Y year%m month 〆day")
        #Set company name
        ws['B7'] = '{0}You'.format(model['companyName'])
        for i, item in enumerate(model['items']):
            #Set the product name
            ws['B'+str(i+25)] = '  {0}'.format(item['itemName'])
            #Set quantity
            ws['D'+str(i+25)] = item['quantity']
            #Set unit price
            ws['E'+str(i+25)] = item['price']

        #Download in Excel format
        self.set_header('Cache-Control',
                        'no-store, no-cache, must-revalidate, max-age=0')
        self.set_header(
            'Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        fileName = "Invoice.xlsx"
        self.set_header('Content-Disposition',
                        "attachment; filename=\"{}\"".format(fileName))
        self.write(save_virtual_workbook(wb))

def make_app():
    return tornado.web.Application(
        [
        (r"/html", htmlHandler),
        (r"/json", jsonHandler),
        (r"/excel", prtInvoice),
        ],
        debug=True,
    )
ws['B7'] = 'Hello'

The feature of this module is that you can set and read data in Excel cells like this.

Run & browse

You can download the Excel file by directly specifying the URL as shown below. (Saved directly in the client download folder)

スクリーンショット 2020-08-24 18.54.22.png

When you open the downloaded Excel file スクリーンショット 2020-08-24 18.56.04.png Yes, I managed to display that kind of data

Recommended Posts

Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
Introduction to Python Hands On Part 1
Introduction to Python language
Introduction to OpenCV (python)-(2)
Introduction to PyQt4 Part 1
Introduction to Tornado (1): Python web framework started with Tornado
Introduction to Python Django (2) Win
Introduction to serial communication [Python]
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
Introduction to Ansible Part ③'Inventory'
Introduction to Python For, While
Introduction to Python numpy pandas matplotlib (~ towards B3 ~ part2)
Introduction to Ansible Part ④'Variable'
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
An introduction to Python that even monkeys can understand (Part 3)
Introduction to Python scikit-learn, matplotlib, single-layer algorithm (~ towards B3 ~ part3)
An introduction to Python that even monkeys can understand (Part 1)
An introduction to Python that even monkeys can understand (Part 2)
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Introduction to Python Numerical Library NumPy
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python for non-engineers
Introduction to Python Django (2) Mac Edition
Introduction to Ansible Part 1'Hello World !!'
[AWS SAM] Introduction to Python version
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
[Python Tutorial] An Easy Introduction to Python
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part2-
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part4-
Solving AOJ's Algorithm and Introduction to Data Structures in Python -Part3-
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 28. Collective type
[Introduction to Python] How to use class in Python?
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Udemy Python3 + Application] 48. Function definition
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)
A super introduction to Python bit operations
[Introduction to Udemy Python 3 + Application] 10. Numerical values
[Introduction to Udemy Python3 + Application] 21. Tuple type
[Introduction to Udemy Python3 + Application] 45. enumerate function