读取Excel数据:
import openpyxl
def read_excel(filepath, sheetname):
workbook = openpyxl.load_workbook(filepath)
sheet = workbook[sheetname]
print(sheet.max_row, sheet.max_column) # 获取sheet数据的总行数/总列数
sheetdata = []
for i in range(2, sheet.max_row + 1): # 从第二行开始取值
linedata = []
for j in range(1, sheet.max_column + 1):
# sheet.cell(row=i, column=j)
data = sheet.cell(i, j).value # 获取单元格值
linedata.append(data) # 得到行数据值
sheetdata.append(linedata)
print(sheetdata)
read_excel("data.xlsx", "user_password")
写入Excel数据:
import openpyxl
def write_file():
workbook = openpyxl.load_workbook("data.xlsx")
sheet = workbook.create_sheet("乘法表") #添加工作表,默认插入最后
# ws2 = workbook.create_sheet("Mysheet", 0) #添加工作表,插入开始的位置
for i in range(1,10):
for j in range(1,i+1):
celldata = "{} * {} = {}".format(i,j,i*j)
# sheet.cell(i,j,celldata) #写入单元格数据
sheet.cell(i,j).value=celldata
workbook.save("data.xlsx") #保存
write_file()
结果:
注意:
如果提示“PermissionError: [Errno 13] Permission denied”检查文件是否是在打开状态;