python学习-openpyxl模块

###############创建工作表#######################
使用openpyxl创建表
from openpyxl import Workbook
import time

book = Workbook()
sheet = book.active

sheet['A1'] = 56
sheet['A2'] = 43

now = time.strftime("%x")
sheet['A3'] = now

book.save("sample.xlsx")
实现效果
路径:
C:/Users/Administrator/PycharmProjects/pythonProject

 

 

指定其他路径

book.save("C:\\Users\\Administrator\\Desktop\\sample.xlsx")
另外一种写法:
book.save("C:/Users/Administrator/Desktop/sample.xlsx")

 

 

 

 

###############读取单元格内容#######################
import openpyxl

book = openpyxl.load_workbook('C:/Users/Administrator/Desktop/t.xlsx')

sheet = book.active

a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)
b1 = sheet.cell(row=1,column=2)
b2 = sheet.cell(row=2,column=2)
b3 = sheet['B3']

print(a1.value)
print(a2.value)
print(a3.value)
print(b1.value)
print(b2.value)
print(b3.value)


print(a1.value,b1.value)
print(a2.value,b2.value)
print(a3.value,b3.value)
实现效果如下:

 

###############读取多行多列单元格内容#######################
#!/usr/bin/env python

import openpyxl

book = openpyxl.load_workbook('C:/Users/Administrator/Desktop/t.xlsx')

sheet = book.active

cells = sheet['A1': 'B6']

for c1, c2 in cells:
print("{0:8} {1:8}".format(c1.value, c2.value))

 

posted @ 2023-07-21 11:01  往事已成昨天  阅读(15)  评论(0编辑  收藏  举报