[英]How to detect protected worksheet in excel workbook using Python xlwings?
[英]Creating excel workbook using excel worksheet (with required condition) using python
我在目錄中有 8 個 excel 文件。 在這 8 個 excel 文件中,我想使用幾個工作表(只有幾個)創建一個 excel 工作簿,然后使用其余工作表創建另一個工作簿。 我編寫的代碼如下 -
from pathlib import Path # Standard Python Module
import time # Standard Python Module
import xlwings as xw # pip install xlwings
# Adjust Paths
BASE_DIR = Path(__file__).parent
SOURCE_DIR = BASE_DIR / 'Region'
OUTPUT_DIR = BASE_DIR / 'Output'
# Create output directory
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
# Using 5 excel files from the 8 excel file list as mentioned above
include_ws = ['US-CAN ABS','US-CAN CMBS RMBS','US-CAN CDO','US-CAN Cov Bonds','Reason Codes Description']
excel_files = Path(SOURCE_DIR).glob('*.xlsx')
# Create timestamp
t = time.localtime()
timestamp = time.strftime('%Y-%m-%d_%H%M', t)
with xw.App(visible=False) as app:
combined_wb = app.books.add()
for excel_file in excel_files:
wb = app.books.open(excel_file)
for sheet in wb.sheets:
if sheet.name in include_ws:
sheet.copy(after=combined_wb.sheets[0])
wb.close()
combined_wb.sheets[0].delete()
combined_wb.save(OUTPUT_DIR / f'all_worksheets_{timestamp}.xlsx')
combined_wb.close()
收到以下錯誤
com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'A workbook must contain at least one visible worksheet. \n\nTo hide, delete, or move the selected sheet(s), you must first insert a new sheet or unhide a sheet that is already hidden.', 'xlmain11.chm', 0, -2146827284), None)
有什么建議嗎?
基本上,該錯誤意味着您正在嘗試刪除工作簿中唯一的工作表,這是不可能的。 在嘗試刪除之前,您似乎沒有進行任何檢查。
IE
您創建工作簿“combined_wb”,然后如果來自“wb”的工作表在您的列表中,則復制“include_ws”。 但是,如果沒有,則不會將工作表復制到“combined_wb”,因此僅保留“Sheet1”。 然后您嘗試刪除“Sheet1”,這是不可能的,因為錯誤顯示“工作簿必須包含至少一個可見的工作表。 '
在調用刪除行之前,您應該確認已復制工作表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.