如何在 Python 中读写 Excel 文件
web前端开发
共 5031字,需浏览 11分钟
·
2021-11-15 18:43
pip install openpyxl
#import libraries
from openpyxl import load_workbook
wb = load_workbook("Excel.xlsx")
sheet = wb.active
#import libraries
from openpyxl import load_workbook
#Selecting specific sheet
wb = load_workbook("Excel.xlsx")
sheet = wb.worksheets[0] # 0 1 2 3 or any
单元格读数
列读
Name age salary
Haider 21 $56,000
John 24 $36,000
Jim 20 $26,000
Sam 26 $76,000
Willaim 22 $46,000
#import libraries
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.active
#reading cell
print("First cell: ", sheet['A1'].value)
print("Second cell: ", sheet['A6'].value)
First cell: Name
Second cell: Willaim
cells = sheet['A2':'C2']
for c1, c2, c3 in cells:
print(c1.value, c2.value, c3.value)
#import libraries
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.active
#reading specific column
cell1 = sheet.cell(row = 1, column = 1).value
cell2 = sheet.cell(row = 1, column = 2).value
cell3 = sheet.cell(row = 1, column = 3).value
print(cell1, cell2 ,cell3)
#import libraries
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.active
#reading specific column
cell1 = sheet.cell(row = 1, column = 1).value
cell2 = sheet.cell(row = 1, column = 2).value
cell3 = sheet.cell(row = 1, column = 3).value
print(cell1, cell2 ,cell3)
Name
Haider
John
Jim
Sam
Willaim
单元格写入
行列书写
#import libraries
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.active
#reading specific column
columns = sheet["A1"].value="Name"
columns = sheet["B1"].value="Age"
columns = sheet["C1"].value="Salary"
wb.save("excel.xlsx")
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.active
sheet.cell(row=1, column=1).value="Name"
sheet.cell(row=1, column=2).value="Age"
sheet.cell(row=1, column=3).value="Salary"
wb.save("excel.xlsx")
#import libraries
from openpyxl import load_workbook
wb = load_workbook("excel.xlsx")
sheet = wb.worksheets[0]
name=["John", "Dennis", "Ferb", "Candas", "Tadashi"]
salary=["$45000","$78000","$34000","$71000","$98000"]
sheet.cell(row=1, column=1).value="Name"
sheet.cell(row=1, column=2).value="Salary"
j=2
for i in range(0,5):
sheet.cell(row=j, column=1).value=name[i]
sheet.cell(row=j, column=2).value=salary[i]
j+=1
wb.save("excel.xlsx")
学习更多技能
请点击下方公众号
评论