The python module openpyxl

Work is often used excel table, in python, we can use openpyxl easily operate it. This article first introduces the basic two quick examples of usage openpyxl.

Example 1

Shows the creation of a new workbook, activate the default form, assign and save the file in rows.

from openpyxl Import the Workbook 

WB = the Workbook ()
 # activate default form 
WS = wb.active
 # in the unit of the input 
Row = [ " A1 " , " Bl " , " a C1 " ] 
ws.append (Row) 
# save file 
wb.save ( " 1.xlsx " )

At this time you will get excel file named "1.xlsx", which excel file only one default form, the default form the first line is assigned a.

Example 2

Shows the load workbooks, create a new form, and save the file assigned to the cell form.

from openpyxl Import load_workbook 

# load file 
WB = load_workbook ( " 1.xlsx " )
 # create a new form 
WS = wb.create_sheet ( " My Sheet " )
 # to cell A3 assignment 
WS [ ' A3 ' ] = 10
 # Save File 
wb.save ( " 2.xlsx " )

At this time, the excel document will be called "2.xlsx", which excel file containing the default and the new two forms, which form new cells are assigned the A3.

 

Through the above two examples, have to openpyxl after a rough idea. Start to introduce openpyxl more basic usage.

Modify the form name

ws.title = "new title"

Action Specify the name of the form

ws1 = wb["new title"]
ws1['A3'] = 10

Traversing the workbook form name

for sheet in wb:
    print(sheet.title)

Copy Form

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

 Assigned to the cell

# Method. 1 
WS [ ' A4 ' ] = 10
 # Method 2 
ws.cell (Row =. 4, column =. 1, value = 10)

Use datetime format of the assignment

import datetime
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# set date using a Python datetime
ws['A1'] = datetime.datetime(2010, 7, 21)
print(ws['A1'].number_format)
print(ws['A1'].value)

 Results are as follows:

yyyy-mm-dd h:mm:ss
2010-07-21 00:00:00

Using the formula assignment

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# add a simple formula
ws["A1"] = "=SUM(1, 1)"
wb.save("formula.xlsx")

Merge / Unmerge cells

from openpyxl.workbook import Workbook

wb = Workbook()
ws = wb.active
# 方法1
ws.merge_cells('A2:D2')
ws.unmerge_cells('A2:D2')
# 方法2
ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)
ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)

wb.save("merge.xlsx")

 Add Chart

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

wb = Workbook()
ws = wb.active
for i in range(10):
    ws.append([i])

values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)
ws.add_chart(chart, "E15")
wb.save("SampleChart.xlsx")

In addition to the common usage, openpyxl more and more powerful need to understand the venue and official documents.

 Reference material

Guess you like

Origin www.cnblogs.com/zhuosanxun/p/12470262.html