from openpyxl import load_workbook, Workbook
写
wb_xlsx = Workbook()
wb_xlsx.create_sheet(title='花名册',index=0)
ws_xlsx = wb_xlsx.active
ws_xlsx.append(['a', 'b', 'c', 'd', 'e', 'f'])
for i in range(6):
ws_xlsx.append([1,2,3,4,5,6])
wb_xlsx.save(filename='openpyxl_file.xlsx')
追加单元表
wb = load_workbook('openpyxl_file.xlsx')
wb.create_sheet(title='Word',index=0)
ws = wb.active
ws.append(['a', 'b', 'c', 'd', 'e', 'f'])
for i in range(3):
ws.append([1,1,1,1,1,1])
wb.save(filename='openpyxl_file.xlsx')
读
第一种方式用openpyxl读
workbook = load_workbook('D:\\sbd\\baidu\\openpyxl_file.xlsx')
sheetnames = workbook.sheetnames
print(sheetnames)
table = workbook.active
for sheetname in sheetnames:
table = workbook[sheetname]
rows = table.max_row
cols = table.max_column
for row in range(rows):
for col in range(cols):
data = table.cell(row + 1, col + 1).value
print(data, end=' ')
pandas读
import pandas as pd
result_a = pd.read_excel(r'./openpyxl_file.xlsx', sheet_name=sheetnames)
for sheetname in sheetnames:
result_a[sheetname].fillna('',inplace=True)
for res in result_a[sheetname].index.values:
row = result_a[sheetname].loc[res,result_a[sheetname].columns.values].to_dict()
print(row)
追加
wb = load_workbook('D:\\sbd\\baidu\\openpyxl_file.xlsx')
sheet1 = wb['Word']
sheet2 = wb.copy_worksheet(sheet1)
sheet2.title = "复制工作表"
wb.save(filename='openpyxl_file.xlsx')
|