我正在尝试在 Excel 中复制并粘贴包含公式 =IMAGE(Url) 的单元格的值。结果是嵌入单元格中的图像,并且不再链接到 URL。
我可以使用 pywin32 使用以下脚本来完成此操作:
ws.Range(f"C2:C{last_row}").PasteSpecial(Paste=win32.constants.xlPasteValues)
鉴于我的目标是在 Azure Function App 中自动化整个脚本,我知道 pywin32 不是理想的解决方案?是否有使用 openpyxl 或其他库的上述脚本的等效项?
谢谢!
下面的示例代码使用Python中的
openpyxl
库来处理Excel文件并用URL替换图像公式。函数 paste_image_values
加载 Excel 工作簿,迭代特定单元格,从图像公式中提取 URL,并将公式替换为 URL。
from openpyxl import load_workbook
import requests
from io import BytesIO
from PIL import Image
# Load the Excel workbook
workbook = load_workbook("C://Users//v-sapujari//Book1.xlsx")
ws = workbook.active
# Iterate through the cells
for row in ws.iter_rows():
for cell in row:
if cell.data_type == 'f' and cell.value.startswith('=IMAGE'):
# Evaluate the formula to get the image URL
url = cell.value.split('(')[1].split(')')[0]
# Fetch the image from the URL
response = requests.get(url)
image = Image.open(BytesIO(response.content))
# Save the image to a file (or do whatever you want with it)
image_file_name = f'image_{cell.row}_{cell.column}.jpg'
image.save(image_file_name)
# Set the cell value to the image file name
cell.value = image_file_name
# Save the modified workbook
workbook.save('modified_excel_file.xlsx')
它从 Excel 文件中提取图像,其中图像 URL 被指定为公式,然后将这些图像保存在本地并使用本地图像文件名更新 Excel 文件。
使用http触发azure函数。使用的包装
azure-functions
、openpyxl
、requests
和 Pillow
import azure.functions as func
import logging
from openpyxl import load_workbook
import requests
from io import BytesIO
from PIL import Image
def process_excel():
# Load the Excel workbook (Replace the file path with the appropriate location)
workbook = load_workbook("C://Users//Book1.xlsx")
ws = workbook.active
# Iterate through the cells
for row in ws.iter_rows():
for cell in row:
if cell.data_type == 'f' and cell.value.startswith('=IMAGE'):
# Evaluate the formula to get the image URL
url = cell.value.split('(')[1].split(')')[0]
# Fetch the image from the URL
response = requests.get(url)
image = Image.open(BytesIO(response.content))
# Save the image to a file (or do whatever you want with it)
image_file_name = f'image_{cell.row}_{cell.column}.jpg'
image.save(image_file_name)
# Set the cell value to the image file name
cell.value = image_file_name
# Save the modified workbook
workbook.save('modified_excel_file.xlsx')
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
# Process the Excel file
process_excel()
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200
)