openpyxl主要是为了和excel进行交互,常用的几种方法如下
包括了读取excel,创建excel等操作,废话不多说,看代码
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl import workbook
def readANDsppend():
workbook = load_workbook(filename='sample.xlsx')#打开sample.xlsx,这个表格需要是已经存在的
sheet1 = workbook.create_sheet("Teacher")#创建Teacher页
sheet2 = workbook.create_sheet("Sheet1")#创建sheet1页
sheet3 = workbook['Sheet1']#选中sheet1这一页,也可以不创建 ,sheet1存在的话,直接调用就行了
data1 = ["xiaoming", "25", "汉子"]#插入数据,
#name='zhangpan',age='25',sex='汉子'
#data2=[name,age,sex]
sheet3.append(data1)
workbook.save(filename='sample.xlsx')
#创建sample.xlsx,并创建一个名为Student的sheet,然后写入数据并保存
def CreatXLS():
wb = Workbook() #创建一个workbook
sheet1 = wb.create_sheet("Student")#创建student页
sheet2 = wb.create_sheet("Teacher")#创建teacher页
data1 = ["xiaoming", "25", "汉子"]
sheet2.append(data1)
wb.save("sample.xlsx")
#输出每个sheet的名字
def GetSheetName():
workbook = load_workbook(filename='sample.xlsx')
print(workbook.sheetnames)#以列表形式输出该workbook中所有的worksheet
for sheet in workbook:#循环输出workbook的各个worksheet的名称
print(sheet.title)
workbook.save('sample.xlsx')
def ReadxlsInfo():
wb=load_workbook(filename='sample.xlsx')#打开Excel
sheet=wb['Student']#选中sheet
print(sheet['A1'].value)#打印A1格的内容
print(sheet[1][0].value) #这里也是A1值,行索引从1、列索引从0算起
wb.save(filename='sample.xlsx')
ReadxlsInfo()
,