當實際工作需要把excel表的數據讀取出來,或者把一些統計數據寫入excel表中時,一個設計豐富,文檔便於尋找的模塊就會顯得特別的有吸引力,本文對openpyxl模塊的一些常見用法做一些記錄,方便工作中查詢(好記性不如爛筆頭)
author:he
qq:760863706
python:3.5
date:2018-9-14
1:安裝openpyxl
pip install openpyxl
1
2:excel表讀取數據(.xlsx)
import openpyxl
filepath = 'sample.xlsx'
wb = openpyxl.load_workbook(filepath)
#獲取全部表名
sheetnames = wb.sheetnames
#切換到目標數據表
#ws = wb[]
ws = wb['sheet2']
#表總行數
max_row = ws.max_row
#表總列數
max_col = ws.max_column
for x in range(1,max_row):
#獲取表中x行1列的值
cell_data = ws.cell(row=x,column=1).value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
3:已存在excel表追加數據
import openpyxl
filepath = 'sample.xlsx'
wb = openpyxl.load_workbook(filepath)
#切換到目標數據表
#ws = wb[]
ws = wb['sheet2']
#待填充數據
data = [[1,2,3],[4,5,6]]
for x in data:
ws.append(x)
savename = 'update_excel.xlsx'
wb.save(savename)
1
2
3
4
5
6
7
8
9
10
11
12
4:創建新excel表
import openpyxl
filepath = 'new_excel.xlsx'
wb = openpyxl.Workbook()
#默認表sheet1
ws1 = wb.active
#更改表名
ws1.title = 'new_sheet_name'
#創建sheet2表
ws2 = wb.create_sheet('sheet2')
ws1.cell(row=1,column=1,value='sheet1表1行1列的值').value
ws2.cell(row=2,column=2,value='sheet2表2行2列的值').value
wb.save(filepath)
————————————————
版權聲明:本文為CSDN博主「weixin_38336920」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_38336920/article/details/82703209