使用xlwings或openpyx访问win32com创建的Excel对象

2024-04-27 05:03:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个脚本,该脚本需要访问包含对其他Excel工作簿的许多外部引用的Excel工作簿。该脚本应该清点包含引用的主工作簿的每个工作表中的单元格,将相关信息(工作表、单元格坐标、公式、计算值)复制到pandas数据框中。

我使用win32com创建一个Excel应用程序实例,其中DisplayAlerts和Update链接已经关闭。在我的场景中,这两个设置会干扰openpyxl和xlwings。

是否可以使用xlwings或openpyxl包在活动Excel应用程序中访问win32com启动的活动Excel工作簿?

假设我使用以下代码创建一个名为win32_wb的工作簿对象:

import xlwings as xw
import openpyxl
import win32com.client as win32
from win32com.client import DispatchEx
import pandas as pd

file_1 = r"C:\Users\me\Documents\ext_ref.xlsx"

# Create an instance of Excel
excel_1 = win32.DispatchEx('Excel.Application')

# Ensure the Excel instance is not shown in the U/I (runs faster)
excel_1.Visible = False

# disable Warning & Link Update messages for excel_1
run_macro(excel_1)

# Open the ref workbook as an object in the Excel instance  
wb = excel_1.workbooks.open(file_1)

# Need to access the object with openpyxl or xlwings

Tags: theinstanceimport脚本应用程序pandasasupdate