import openpyxl
'''
创建并保存工作表
'''
wb = openpyxl.load_workbook('test.xlsx')
print(wb.get_sheet_names())
sheet = wb.active
print(sheet)
print(sheet.title)
# 更改Sheet表名字
sheet.title = 'Spam Bacon Eggs Sheet'
print(wb.get_sheet_names())
# 保存生效
wb.save('copy_test.xlsx')
print('---------------------')
'''
创建和删除工作表,利用create_sheet() and remove_sheet()方法,可以在工作薄中添加或删除工作表
create_sheet()方法返回一个新的Worksheet对象,index指定索引,title为名称
'''
test = openpyxl.Workbook()
print(test.get_sheet_names())
print(test.create_sheet())
print(test.get_sheet_names())
print(test.create_sheet(index=0,title='first sheet'))
print(test.get_sheet_names())
print(test.create_sheet(index=2,title='Middle sheet'))
print(test.get_sheet_names())
test.remove_sheet(test.get_sheet_by_name('Middle sheet'))
test.remove_sheet(test.get_sheet_by_name('Sheet1'))
print(test.get_sheet_names())
print('----------------')
'''
将值写入单元格
'''
sheet = wb.get_sheet_by_name('Sheet2')
sheet['A1'] = 'Hello world!'
print(sheet['A1'].value)
wb.save('ceshi.xlsx')
---------------------
['Sheet']
<Worksheet "Sheet1">
['Sheet', 'Sheet1']
<Worksheet "first sheet">
['first sheet', 'Sheet', 'Sheet1']
<Worksheet "Middle sheet">
['first sheet', 'Sheet', 'Middle sheet', 'Sheet1']
['first sheet', 'Sheet']
----------------
Hello world!
网友评论