覺得有用,網上抄的
這篇文章主要介紹了Python openpyxl模塊原理及用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
此模塊不是Python內置的模塊需要安裝,安裝方法如下
pip install openpyxl
注意:
此模塊只支持offce 2010,即是電子表格后綴是*.xlsx
1、openpyxl模塊常用函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import
openpyxl
wb
=
openpyxl.load_workbook(
'example.xlsx'
)
##### 工作表常用操作
print
(wb.active)
# 獲取電子表格Worksheet是否有數據
print
(wb.read_only)
# 是否是以只讀方式打開
print
(wb.encoding)
# 獲取電子表格的編碼
print
('', wb.properties)
# 獲取電子表格屬性如:標題、作者、創建時間等
print
(wb.worksheets)
# 獲取工作表名
print
(wb.get_sheet_names())
# 獲取工作表的所有名字
print
(wb.sheetnames)
# 獲取工作表的所有名字跟wb.get_sheet_names()一樣的功能
print
(wb.get_sheet_by_name(
'Sheet1'
))
# 通過工作表的名字,獲取Worksheet對象操作電子表格
print
(wb.create_sheet(
'python創建的工作表'
))
# 創建的工作表,記得用save保存,才保存到硬盤上
print
(wb.copy_worksheet(wb[
'Sheet1'
]))
# 復制工作表
#### 工作表的常用操作
sheet1_obj
=
wb[
'Sheet1'
]
print
(sheet1_obj.title)
# 工作表的標題
print
(sheet1_obj.dimensions)
# 獲取表格大小,返回格式如:A1:D6
print
(sheet1_obj.max_row)
# 表格最大行數
print
(sheet1_obj.min_row)
# 表格最小行數
print
(sheet1_obj.max_column)
# 表格最大列數
print
(sheet1_obj.min_column)
# 表格最小列數
print
(sheet1_obj.rows)
# 按行獲取單元格(Cell對象)
print
(sheet1_obj.columns)
# 按列獲取單元格(Cell對象)
print
(sheet1_obj.freeze_panes)
# 凍結窗格
print
(sheet1_obj.values)
# 按行獲取表格的內容(數據)
print
(sheet1_obj.iter_rows())
#迭代器方式,按行獲取所有單元格(Cell對象)
print
(sheet1_obj.iter_columns())
#迭代器方式,按列獲取所有單元格(Cell對象)
sheet1_obj.append([
'1列'
,
'2列'
,
'3列'
,
'4列'
])
#往工作表最后一行插入多列數據
#### 單元格的常用操作
sheet1_obj.merged_cells
#合並單元格
sheet1_obj.unmerge_cells
#取消合並單元格
print
(sheet1_obj[
'A2'
].row)
# 獲取行數
print
(sheet1_obj[
'A2'
].column)
# 獲取列數
print
(sheet1_obj[
'B1'
].value)
#獲取單元格的值
wb.save(
'example.xlsx'
)
#保存單元格
|
2、利用openpyxl模塊創建一張電子表格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from
openpyxl
import
Workbook
wb
=
Workbook()
# print(wb.get_sheet_names()) # 獲取工作表的名字
ws
=
wb.get_sheet_by_name(
'Sheet'
)
# 獲取Sheet工作表對象
# print(ws.title) # 獲取工作表的標題
ws.title
=
'Student'
# 設置新的工作表
# 設置內容
ws[
'A1'
]
=
'Hello World'
import
datetime
ws[
'A2'
]
=
datetime.datetime.now()
wb.save(
'new_sample.xlsx'
)
|
運行效果
3、利用openpyxl模塊對電子表格運算操作(求和數、平均數)
表格例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import
openpyxl
from openpyxl.styles
import
Alignment
def process_worksheet(sheet):
avg_column = sheet.max_column + 1
# 平均數,存放在最后一列
sum_column = sheet.max_column + 2
# 求和,存放在最后第二列
for
row in sheet.iter_rows(min_row=2, min_col=2):
scores = [cell.value
for
cell in row]
# 獲取一行的值
sum_score = sum(scores)
# 求一行的和
avg_score = sum_score / len(scores)
# 求一行的平均數
avg_cell = sheet.cell(row=row[0].row, column=avg_column)
sum_cell = sheet.cell(row=row[0].row, column=sum_column)
avg_cell.value = avg_score
# 定位到單元格,設置總分
sum_cell.value = sum_score
# 定位到單元格,設置平均分
# 設置對齊方式,水平是右對齊,垂直是居中
align = Alignment(horizontal=
'left'
, vertical=
'center'
, wrap_text=True)
avg_cell.alignment = align
sum_cell.alignment = align
# 設置平均分和總分的標題
sheet.cell(row=1, column=avg_column).value =
'平均分'
sheet.cell(row=1, column=sum_column).value =
'總分'
def main():
wb = openpyxl.load_workbook(
'example.xlsx'
)
sheet = wb.get_sheet_by_name(
'Sheet1'
)
process_worksheet(sheet)
wb.save(
'example.xlsx'
)
if
__name__ ==
'__main__'
:
main()
|
運行效果
4、多張電子表格合並為一張電子表格
准備3張電子表格
員工1.xlsx
員工2.xlsx
員工3.xlsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import
openpyxl
import
glob
import
os
def
merge_xlsx_files(xlsx_files):
wb
=
openpyxl.load_workbook(xlsx_files[
0
])
# 打開第一張電子表格
ws
=
wb.active
# 激活 worksheet
ws.title
=
'merged result'
# 合並結果
for
filename
in
xlsx_files[
1
:]:
workbook
=
openpyxl.load_workbook(filename)
sheet
=
workbook.active
# 激活 worksheet
for
row
in
sheet.iter_rows(min_row
=
2
):
# 從第二行開啟迭代
values
=
[cell.value
for
cell
in
row]
# 返回一列的值,以列表類型
ws.append(values)
# 把列表增加到新的表格里面
return
wb
def
get_all_xlsx_files(path):
"""指定后綴名,獲取所有跟后綴相關的文件類型,返回列表"""
xlsx_files
=
glob.glob(os.path.join(path,
'*.xlsx'
))
sorted
(xlsx_files, key
=
str
.lower)
# 排序
return
xlsx_files
def
main():
path
=
os.path.join(os.path.dirname(os.getcwd()),
'臨時測試'
,
'excels'
)
# 目錄自行配置
xlsx_files
=
get_all_xlsx_files(path)
wb
=
merge_xlsx_files(xlsx_files)
wb.save(
'merge_data.xlsx'
)
# 保存數據到硬盤
if
__name__
=
=
'__main__'
:
main()
|
運行效果(硬盤多出一張電子表格 merge_data.xlsx)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。