Openpyxl Cheat Sheet



Openpyxl is a Python library used to read and write Excel files (xlsx/xlsm/xltx/xltm files). This module allows the Python programs to read and modify the spreadsheet. XLSX file is the default file format for Microsoft Excel. It is based on the Office Open XML standard. # 获得当前正在显示的sheet, 也可以用wb.getactivesheet # 除了用下标的方式获得,还可以用cell函数, 换成数字,这个表示B2 for cell in she.

Sheet

Opening Excel Documents with OpenPyXL¶

Openpyxl is a library in Python with which one can perform the different mathematic operations in an excel sheet. In this tutorial, we are going to learn the implementation of mathematical functions available in openpyxl library. Mathematical operations like. Openpyxl.worksheet.worksheet module¶. Worksheet is the 2nd-level container in Excel. Class openpyxl.worksheet.worksheet.Worksheet (parent, title=None) source ¶. Bases: openpyxl.workbook.child.WorkbookChild Represents a worksheet. Do not create worksheets yourself, use openpyxl.workbook.Workbook.createsheet instead. BREAKCOLUMN = 2¶ BREAKNONE = 0¶. First go to your python folder and create a new MS Excel file there. Name it as 'testdel.xlsx' the file will have three sheets by default. Please note that the file will be empty and hence it will not delete any of your important Excel data. When you practice with this test file, you can proceed to deleting a sheet from your actual Excel Workbook.

Getting Sheets from the Workbook¶

Getting Cells from the Sheets¶

Openpyxl cheat sheet

Specifying a column by letter can be tricky to program, especially because after column Z, the columns start by using two letters: AA, AB, AC, and so on. As an alternative, you can also get a cell using the sheet’s cell() method and passing integers for its row and column keyword arguments. The first row or column integer is 1, not 0.<Cell Sheet1.B1>

Converting Between Column Letters and Numbers¶

Openpyxl Cheat Sheet

Getting Rows and Columns from the Sheets¶

You can slice Worksheet objects to get all the Cell objects in a row, column, or rectangular area of the spreadsheet. Then you can loop over all the cells in the slice.

Creating and Saving Excel Documents¶

Openpyxl Cheat Sheet

Creating and Removing Sheets¶

The create_sheet() method returns a new Worksheet object named SheetX, which by default is set to be the last sheet in the workbook. Optionally, the index and name of the new sheet can be specified with the index and title keyword arguments.

Writing Values to Cells¶

Openpyxl copy sheet

Setting the Font Style of Cells¶

Font Objects¶

Keyword Arguments for Font

Keyword argumentdata typeDescription
namestringThe font name, such as ‘Calibri’ or ‘Times New Roman’
sizeintegerThe point size
boldbooleanTrue, for bold font
italicbooleanTrue, for italic font

Formulas¶

This will store =SUM(B1:B8) as the value in cell B9. This sets the B9 cell to a formula that calculates the sum of values in cells B1 to B8.

Openpyxl Sheet By Name

Setting Row Height and Column Width¶