python operation using openpyxl execl

 

 

openpyxl

openpyxl can be used to operate excel, but can only operate xlsx files can not be operated xls file.

Mainly used three concepts: Workbooks, Sheets, Cells.
Workbook is an excel workbook;
Sheet worksheet is a worksheet;
the Cell is a simple grid.
openpyxl revolves around three concepts: Open the Workbook, locate Sheet, Operation Cell.

 

Reading and creating

Read Workbooks

May be introduced openpyxl.load_workbook () to open an existing workbook:

>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
>>> print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']

 

Creating Workbooks and Sheets

In the beginning of openpyxl use, you do not need to create a file in the file system directly, only need to import Workbook class and start using it:

>>> from openpyxl import Workbook
>>> wb = Workbook()

A workbook always creates at least a worksheet (worksheet), you can go to get by openpyxl.workbook.Workbook.active () this property:

>>> ws = wb.active

The value of this function uses _active_sheet_index this property, the default setting is 0, unless you specify a value, otherwise always get to the first worksheet.

You can use openpyxl.workbook.Workbook.create_sheet () to create a new worksheet:

>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)# or
>>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position

Is automatically created when the foot is created when a subject name, created in accordance with (Sheet, Sheet1, Sheet2, ...) the list of names, you can use tiitle properties to modify the name:

>>> ws.title = "New Title"

Once you give the name of a worksheet, you can go to get this worksheet through a key:

>>> ws3 = wb["New Title"]

You can use openpyxl.workbook.Workbook.sheetnames () Gets all the attribute name of the subject's foot:

>>> print(wb.sheetnames)['Sheet2', 'New Title', 'Sheet1']

Iterate through all the feet standard:

>>> for sheet in wb:
... print(sheet.title)

You can use openpyxl.workbook.Workbook.copy_worksheet () This attribute copy a worksheet:

>>> source = wb.active
>>> target = wb.copy_worksheet(source)

Note: Only cells and styles can be copied, can not copy worksheets between workbooks, you can copy worksheets in a workbook in

 

Data Manipulation

Get a cell

Now that we know how to access a worksheet, we can begin to modify the contents of the cell. (A cell is a cell)
cell can be obtained by direct key:

>>> c = ws['A4']

This will return a cell or cell to create a non-existent. The value of the cell can be directly assigned:

>>> ws['A4'] = 4

Another method may also be used openpyxl.worksheet.Worksheet.cell ():

>>> d = ws.cell(row=4, column=2, value=10)

Note: When you create a worksheet in memory of them when it does not contain any cell, are created when they first accessed the

Warning: Because the rolling characteristics excel table, rolling out of the cell will be created out, even if there is no access to those cell, for example:

>>> for i in range(1,101):
... for j in range(1,101):
... ws.cell(row=i, column=j)

This will create a 100 * 100 empty cell

Access to multiple cell

Use slices can access multiple cell

>>> cell_range = ws['A1':'C2']

Rows and columns can be easily obtained:

>>> colC = ws['C']
>>> col_range = ws['C:D']
>>> row10 = ws[10]
>>> row_range = ws[5:10]

You can also use openpyxl.worksheet.Worksheet.iter_rows () this method:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
... for cell in row:
... print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.B1>
<Cell Sheet1.C1>
<Cell Sheet1.A2>
<Cell Sheet1.B2>
<Cell Sheet1.C2>

A similar method openpyxl.worksheet.Worksheet.iter_cols () may be:

>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
... for cell in col:
... print(cell)
<Cell Sheet1.A1>
<Cell Sheet1.A2>
<Cell Sheet1.B1>
<Cell Sheet1.B2>
<Cell Sheet1.C1>
<Cell Sheet1.C2>

If you want to iterate over a file of all rows or columns, you can use openpyxl.worksheet.Worksheet.rows () this property:

>>> ws = wb.active
>>> ws['C9'] = 'hello world'
>>> tuple(ws.rows)
((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
(<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
(<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
(<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
(<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
(<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
(<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
(<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
(<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))

Or openpyxl.worksheet.Worksheet.columns () this property:

>>> tuple(ws.columns)
((<Cell Sheet.A1>,
<Cell Sheet.A2>,
<Cell Sheet.A3>,
<Cell Sheet.A4>,
<Cell Sheet.A5>,
<Cell Sheet.A6>,
...
<Cell Sheet.B7>,
<Cell Sheet.B8>,
<Cell Sheet.B9>),
(<Cell Sheet.C1>,
<Cell Sheet.C2>,
<Cell Sheet.C3>,
<Cell Sheet.C4>,
<Cell Sheet.C5>,
<Cell Sheet.C6>,
<Cell Sheet.C7>,
<Cell Sheet.C8>,
<Cell Sheet.C9>))

 


data storage

Once we have a openpyxl.cell.Cell, we can assign to it:

>>> c.value = 'hello, world'
>>> print(c.value)'hello, world'
>>> d.value = 3.14
>>> print(d.value)3.14

It can also be used to infer the type and format:

>>> wb = Workbook(guess_types=True)
>>> c.value = '12%'
>>> print(c.value)
0.12
>>> import datetime
>>> d.value = datetime.datetime.now()
>>> print d.valuedatetime.datetime(2010, 9, 10, 22, 25, 18)
>>> c.value = '31.50'
>>> print(c.value)
31.5

 


Save to File

The most simple and fast to save a workbook is to use openpyxl.workbook.Workbook module openpyxl.workbook.Workbook.save () this method:

>>> wb = Workbook()
>>> wb.save('balances.xlsx')

Warning: This method will not overwrite warning prompt some content
can use the template = True will save a workbook as a template:

>>> wb = load_workbook('document.xlsx')
>>> wb.template = True
>>> wb.save('document_template.xltx')

Or set this property to false (the default) to save it as a file:

>>> wb = load_workbook('document_template.xltx')
>>> wb.template = False
>>> wb.save('document.xlsx', as_template=False)

* Warning: When you save a document in the document template that you should pay attention to the extension (suffix) documents and data description, it may cause the document can not be opened again, the following error formula Example:
Notes following will fail:

Wb = load_workbook >>> ( ' document.xlsx ' )
 >>> # should be saved as .xlsx extension * 
>>> wb.save ( ' new_document.xlsm ' )
 >>> # Excel software can not open this file again 
>>> 
>>> # or 
>>> 
>>> # should specify attributes = True keep_vba 
>>> WB = load_workbook ( ' document.xlsm ' )
 >>> wb.save ( ' new_document.xlsm ' )
 >>> # Excel software can not open this file again 
>>> 
>>> # or 
>>> 
>>> load_workbook wb = (' Document.xltm ' , keep_vba = True)
 >>> # If we need a template file, you must specify the extension .xltm *. 
>>> wb.save ( ' new_document.xlsm ' )
 >>> # Excel software You can not open this file again

 

 

 Description link

 Further reading:

Working with Excel Spreadsheets

openpyxl simple usage

Guess you like

Origin www.cnblogs.com/-wenli/p/11590221.html