#from openpyxl import Workbook
#from openpyxl import load_workbook
import openpyxl
wb = openpyxl.Workbook() # 创建新的工作簿
ws = wb['Sheet'] # 实例化工作表
# ws = wb.active # 默认实例化最后一个工作表
# ws = wb.create_sheet('Sheet1') # 在末尾创建工作表
ws.title = 'Sheet1' # 重命名工作表
ws['A1'] = 'Hello World1' # 写入
ws['B1'] = 'Hello World2' # 写入
ws['C1'] = 'Hello World3' # 写入
ws['A2'] = 'Hello World4' # 写入
ws['B2'] = 'Hello World5' # 写入
ws['C2'] = 'Hello World6' # 写入
#print(ws['A1'].value) # 读取
#保存test.xlsx表格
wb.save('test.xlsx')
wb.close()
#读取test.xlsx表格
wb = openpyxl.load_workbook(filename='test.xlsx')
#wb = load_workbook(filename='sample.xlsx')
sheetnames=wb.sheetnames
print(sheetnames)
worksheet_translate=wb[sheetnames[0]]
print(worksheet_translate)
max_row = worksheet_translate.max_row #总共的行数
print(max_row)
ws = wb.active
for row in ws.rows: # 按行遍历
for cell in row:
value = cell.value #打印出每个单元格的值
if value:
print(value)
结果:
在.py的同目录下生成test.xlsx文件,内容:
['Sheet1']
<Worksheet "Sheet1">
2
Hello World1
Hello World2
Hello World3
Hello World4
Hello World5
Hello World6