09excel存儲
數據存儲:Excel
python內置模塊中是沒有提供處理Excel文件的模塊,想要在python中操作Excel是需要安裝第三方模塊openpyxl,這個模塊中集成了python操作Excel的相關功能。
cmd:pip install openpyxl
需要注意的是 openpyxl處理的Excel文件的后綴是要是xlsx
Excel基本操作
import openpyxl
from openpyxl import workbook
# 打開一個Excel
table = openpyxl.load_workbook('qwer.xlsx')
# 獲取到excel中的所有sheet表名,返回列表
print(table.sheetnames, table.sheetnames[1])
# 選擇操作表格
sheet = table['Sheet2']
print(sheet)
# 拿到所有的sheet
for name in table.sheetnames:
sheet = table[name]
print(sheet.cell(1, 1).value)
# 創建一個excel
print('-'*100)
wb = workbook.Workbook()
sheet = wb.worksheets[0] # sheet = wb['Sheet']
cell = sheet.cell(1, 1)
# 將數據寫入excel
cell.value = 'name'
cell = sheet.cell(2, 1)
cell.value = 'jcx'
# 查看數據行數
max_row = sheet.max_row
print(max_row)
# 保存數據
wb.save('創建excel.xlsx')
獲取數據
import openpyxl
table = openpyxl.load_workbook('qwer.xlsx')
# 選擇操作表格
sheet = table['Sheet2']
print(sheet)
# 獲取表中數據
# 1.獲取某行某列的數據
cell = sheet.cell(1, 1) # Cell 'Sheet1'對象
print(cell.value)
# 2.根據單元格名稱獲取數據 直接得到數據
cell = sheet['A1']
print(cell)
# 3.獲取某一行數據,返回元祖
cell = sheet[1]
print(cell, type(cell))
for data in cell:
print(data.value)
# 獲取所有行數據
print(sheet.rows)
for row in sheet.rows:
print(row, row[1].value)

浙公網安備 33010602011771號