參考文章:Python使用openpyxl讀寫excel文件
- 安裝:
使用管理員模式進(jìn)行pip下載安裝pip install openpyxl
- 從excel文件中讀取數(shù)據(jù)
from openpyxl import load_workbook
# 讀取excel文件
wb = load_workbook('具體路徑//properties.xlsb')
# wb = load_workbook('具體路徑//menus.xls')
# openpyxl不支持xls格式的文件讀取,需要使用xlrd庫來讀取xls文件,
# 或者將xls文件轉(zhuǎn)化為xlsx格式文件
wb = load_workbook('具體路徑//menus.xlsx')
# 也不支持讀取xlsx之外的格式,例如不支持讀取xlsb類型的文件
# 默認(rèn)打開的文件可讀寫
# 獲得所有sheet的名稱
print(wb.get_sheet_names())
# 根據(jù)sheet名字獲得sheet
a_sheet = wb.get_sheet_by_name('Sheet1')
# 獲得sheet名
print(a_sheet.title)
# 獲得當(dāng)前正在顯示的sheet, 也可以用wb.get_active_sheet()
sheet = wb.active
a1 = sheet['A1'] # 位置 A列 1 行
# a1為一個(gè)cell類
print(a1.row) # 返回其行號(hào)
print(a1.column) # 返回其列號(hào)
print(a1.coordinate) # 返回字母+數(shù)字位置編號(hào)
print(a1.value) # 返回其值
print(f'({a1.row}, {a1.column}, {a1.value})')
# 下標(biāo)獲得cell類
a1_too = sheet.cell(row=1, column=2)
print(a1_too.value)
# 獲取最大行與最大列
print(sheet.max_row)
print(sheet.max_column)
# 按照 A1 B1 C1 順序返回
for row in sheet.rows:
for cell in row:
print(cell.value)
# 按照 A1 A2 A3 順序返回
for col in sheet.columns:
for cell in col:
print(cell.value)
# 以上sheet.rows 和sheet.columns均是生成器類型,不能使用索引
# 要想使用,需要轉(zhuǎn)化成list后使用
# 例如list(sheet.rows)[2]得到第三行的tuple對象
# 讀取第一行的所有數(shù)據(jù)
for cell in list(sheet.rows)[0]:
print(cell.value)
# 獲得任意區(qū)間的單元格 使用range函數(shù)
# 獲取前兩列,前三行的區(qū)域數(shù)據(jù)
for i in range(1, 4): # i依次是1,2,3
for j in range(1, 3):
print((sheet.cell(row=i, column=j)).value)
# 切片使用
for row_cell in sheet['A1':'B3']:
for cell in row_cell:
print(cell)
# 每行的單元格構(gòu)成一個(gè)元祖
for cell in sheet['A1':'B3']:
print(cell)
- 寫入數(shù)據(jù)
from openpyxl import Workbook
# excel文件的寫入
wb = Workbook()
# 新建了一個(gè)工作表,尚未保存
print(wb.get_sheet_names())
# 默認(rèn)提供Sheet的表,office 2016 默認(rèn)新建Sheet1
# 直接賦值可以改工作表的名稱
sheet = wb.active
sheet.title = 'Sheet1'
# 可以對工作表Sheet1 Sheet2 建立索引
wb.create_sheet('Data', index=1)
# 這樣新建第二個(gè)工作表:名稱為Data
# 刪除某個(gè)工作表
# remove 按照變量刪除
wb.remove(sheet)
# del 按表格名稱刪除
del wb['Data']
# 新建一個(gè)工作表
wb = Workbook()
# grab the active worksheet
sheet = wb.active
# 直接給單元格賦值
sheet['A1'] = '編號(hào)'
sheet['B1'] = '屬性'
sheet['c1'] = '值'
# append函數(shù)
# 添加一行
row = [1, 2, 3, 4, 5]
sheet.append(row)
# wb.save('test.xlsx')
for i in range(17):
sheet.cell(row=i+2, column=1, value=i+1)
# Save the file
filer = "存儲(chǔ)路徑"
path = filer + "properties.xlsx"
wb.save(path)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。