做班級的活動的網(wǎng)站企業(yè)營銷策劃方案范文
在多個工作簿中批量新增工作表
假設(shè),一個文件夾下面有多個excel文件,需要再每個excel文件中增加一個sheet。
例子:
import os
import xlwings as xw
file_path = 'D:\\TEST\\python與excel'
file_list = os.listdir(file_path)
sheet_name = '產(chǎn)品銷售區(qū)域'
app = xw.App(visible=False,add_book=False)
for i in file_list:
??? if i.startswith('~$'):
??????? continue
??? file_paths = os.path.join(file_path,i)
??? workbook = app.books.open(file_paths)
??? sheet_names = [j.name for j in workbook.sheets]
??? print(sheet_names)
??? if sheet_name not in sheet_names:
??????? workbook.sheets.add(sheet_name)
??????? workbook.save()
app.quit()
上面例子,需要循環(huán)路徑下面所有excel文件,獲得每個excel文件的sheet,判斷準備新增的sheet名稱是否已經(jīng)存在在excel文件中,如果沒有就新增。
其中,[j.name for j in workbook.sheets]? 是一種簡化寫法,循環(huán)讀取excel中文件名返回名稱組成的列表。workbook.sheets.add(sheet_name) 這個add方法就是在excel文件中增加sheet的方法。
在多個工作簿中批量刪除工作表
假設(shè),需要刪除一個文件夾下面多個excel文件中的相同sheet名稱的sheet。
例子:
import os
import xlwings as xw
file_path = 'D:\\TEST\\python與excel'
file_list = os.listdir(file_path)
sheet_name = '訂單表'
app = xw.App(visible=False,add_book=False)
for i in file_list:
??? if i.startswith('~$'):
??????? continue
??? file_paths = os.path.join(file_path,i)
??? workbook = app.books.open(file_paths)
??? for j in workbook.sheets:
??????? if j.name == sheet_name:
??????????? j.delete()
??????????? break
??? workbook.save()
app.quit()
上面,同樣是雙重循環(huán)來讀取每一個sheet來判斷是否是準備刪除的sheet名稱的sheet,其中j.delete()方法,即sheet對象的delete()方法是用來刪除指定sheet的。
在這里j是<class 'xlwings.main.Sheet'>類型。