本文最后更新于:2023年10月22日 下午
PYTHON办公自动化内容,通过使用插件.xlsx / .xlsm / .xltx / .xltm,
操作EXCEL,读取excel的插件为openpyxl
一、读取sheet名称
1 2 3 4 5 6 7 8
| from openpyxl import load_workbook
workbookname = load_workbook(filename=r"C:\Users\pdsat\Desktop\test.xlsx") i = workbookname.sheetnames print(i)
结果: ['电视剧', '动漫', '综艺', '图书书籍漫画', '教育资源', '神站', '小初高教育', '电影', '盘搜1', '考研教育资源', '盘搜2', '游戏软件', '学而思精品内容']
|
二、向表格中插入行数据
使用.append()
在数据后面增加行数据
1 2 3 4 5 6 7 8 9 10 11 12 13
| from openpyxl import load_workbook
workbook_name = load_workbook(filename=r"C:\Users\pdsat\Desktop\test.xlsx") sheet = workbook_name.active print(sheet) data = [ ["唐僧", "https://www.daohangpage.com/site/335.html"], ["导航页面", "https://9kan.online/"], ["hao123", "https://m.hao123.com"] ] for row in data: sheet.append(row) workbook_name.save(filename=r"C:\Users\pdsat\Desktop\test.xlsx")
|
三、合并拆分sheet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| importopenpyxl
myBook=openpyxl.load_workbook(r"c:\users\pdsat\Desktop\A305\录取表.xlsx") mySheet=myBook["录取表"] myRange=list(mySheet.values)
myDisc={}
formyRowinmyRange[3:]: ifmyRow[0]inmyDisc.keys(): myDisc[myRow[0]] += [myRow] else: myDisc[myRow[0]] = [myRow] formyKey, myValueinmyDisc.items(): myNewSheet=myBook.create_sheet(myKey+'录取表') myNewSheet.append(myRange[2]) formyRowinmyValue: myNewSheet.append(myRow) myBook.save(r'C:\Users\pdsat\Desktop\A305\新录取表.xlsx')
|