Python腾讯文档收集表转excel

# 玺乐幼儿园大二班粤康码、行程码截图收集

import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles import Font, Alignment, Border, Side
from openpyxl.worksheet.page import PageMargins
import requests
import os


def getImageType(url):
    # print(url)
    type_index = url.find('type=')
    type_Name = url[-(len(url) - type_index - 5):]
    # print(type_Name)
    return type_Name


def downloadImage(image_name, url):
    type_Name = getImageType(url)
    print(type_Name)
    image = requests.get(url).content
    print(image_name + '正在保存...')
    with open('./img/' + image_name + '.' + type_Name, 'wb')as fp:
        fp.write(image)

    path = os.getcwd()
    return path + "\\img\\" + image_name + '.' + type_Name


def format_border(s_column, s_index, e_column, e_index):
    for row in tuple(newSheet[s_column + str(s_index):e_column + str(e_index)]):
        for cell in row:
            cell.border = bd




def addimg(current_col, current_row, file):
    if os.path.exists(file):
        file_img = Image(file)  # 调用图像函数
        file_img.width, file_img.height = newSize  # 这两个属性分别是对应添加图片的宽高

        dest_sheet.row_dimensions[current_row].height = image_height
        dest_sheet.add_image(file_img, get_column_letter(current_col) + str(current_row))  # 向d列中的单元格内指定添加图片

############################################################################
# 设置文字图片单元格的行高列宽
newSize = (200, 400)
column_width = 27
image_height = 400  # 设置行高,该设置的行高与excel文件中设置的行高值是一样的
text_height = 50  # 设置行高,该设置的行高与excel文件中设置的行高值是一样的
current_row = 5  # 设置开始行
order_num = 0

ft = Font(name=u'微软雅黑', size=11)  # 设置字体
ag = Alignment(vertical='center', horizontal='center', wrapText=True)  # 设置居中,设置换行
bd = Border(left=Side(border_style="thin", color='000000'),
            right=Side(border_style="thin", color='000000'),
            top=Side(border_style="thin", color='000000'),
            bottom=Side(border_style="thin", color='000000'))  # 设置边框格式

# 读取xlsx文件
wb = load_workbook("玺乐幼儿园(大二班)开学健康申报9月15日(收集结果) (2).xlsx")
# 获取表名
sheetname = wb.sheetnames
print(sheetname)
# 选择工作表
# sheet = wb['sheet1'] #精确的表名
sheet = wb.active  # 活动的表
# newSheet = wb.create_sheet("newSheet")

dest = load_workbook("玺乐幼儿园学生返校健康档案-空表.xlsx")
# 获取表名
dest_sheet = dest.active  # 活动的表

max_row = sheet.max_row + 1

for i in range(2, max_row):
    print('##########################')



    姓名 = sheet.cell(row=i, column=column_index_from_string('B'))
    print(姓名.value)
    三区 = sheet.cell(row=i, column=column_index_from_string('C'))
    print(三区.value)

    dest_sheet.cell(current_row, column_index_from_string('A')).value = order_num+1
    dest_sheet.cell(current_row, column_index_from_string('B')).value = 姓名.value
    dest_sheet.cell(current_row, column_index_from_string('C')).value = "大二班"
    dest_sheet.cell(current_row, column_index_from_string('D')).value = 三区.value

    img_0913_url = sheet.cell(row=i, column=column_index_from_string('D'))
    print(img_0913_url.value)
    img_0913_file=downloadImage(姓名.value+'_检测记录_0913',img_0913_url.value)
    addimg(column_index_from_string('E'),current_row,img_0913_file)

    img_0914_url = sheet.cell(row=i, column=column_index_from_string('E'))
    print(img_0914_url.value)
    img_0914_file=downloadImage(姓名.value+'_检测记录_0914',img_0914_url.value)
    addimg(column_index_from_string('F'),current_row,img_0914_file)

    img_0915_url = sheet.cell(row=i, column=column_index_from_string('F'))
    print(img_0915_url.value)
    img_0915_file=downloadImage(姓名.value+'_检测记录_0915',img_0915_url.value)
    addimg(column_index_from_string('G'),current_row,img_0915_file)

    img_ykm_url = sheet.cell(row=i, column=column_index_from_string('G'))
    print(img_ykm_url.value)
    img_ykm_file=downloadImage(姓名.value+'_粤康码_0915',img_ykm_url.value)
    addimg(column_index_from_string('H'),current_row,img_ykm_file)

    img_xcm_url = sheet.cell(row=i, column=column_index_from_string('H'))
    print(img_xcm_url.value)
    img_xcm_file=downloadImage(姓名.value+'_行程码_0915',img_xcm_url.value)
    addimg(column_index_from_string('J'),current_row,img_xcm_file)

    print('-------------------------')
    img_tzr_urls = sheet.cell(row=i, column=column_index_from_string('J'))
    img_tzr_count =len(img_tzr_urls.value.split()) #获取上传了多少个同住人(上传几张图片URL)
    print(img_tzr_count)
    img_tzr_index = 0
    tzr_col =column_index_from_string('K')
    while img_tzr_index < img_tzr_count:
        img_tzr_url =img_tzr_urls.value.split()[img_tzr_index] #根据下标获取一个url
        print(img_tzr_url)
        img_tzr_file=downloadImage(姓名.value+'_同住人_'+str(img_tzr_index),img_tzr_url)
        addimg(tzr_col,current_row,img_tzr_file)

        tzr_col=tzr_col+1
        img_tzr_index = img_tzr_index+1

    current_row =current_row+1
    order_num =order_num+1


print('**********************************************************************')

dest.save('dest.xlsx')

<think>嗯,用户想用Python实现Excel与多个AI模型的交互,包括DeepSeek-R11、文心一言、腾讯元宝、Kimi,然后把结果记录回Excel。首先我得理清楚每个步骤需要做什么。 首先,用户需要从Excel读取问题。Python处理Excel常用的库有openpyxl和pandas。可能pandas更简单,因为可以直接读取成DataFrame,处理起来方便。不过要确保安装这些库,可能需要用pip安装。 接下来,如何调用各个AI模型的API呢?每个模型的接口可能不一样,需要查阅它们的官方文档。比如,文心一言可能有自己的SDK或者REST API,腾讯元宝和Kimi可能也是类似的情况。DeepSeek-R11可能也有特定的接口方式。所以用户需要先注册这些平台的账号,获取API密钥,然后按照文档中的方法发送请求。 然后,发送请求的时候可能需要处理不同的参数,比如模型名称、prompt、temperature等。每个模型的请求格式可能不同,所以需要为每个模型编写对应的函数。比如,调用文心一言可能需要构造特定的JSON数据,而Kimi可能需要不同的headers或者参数。 另外,用户提到要记录思考过程和结果。有些API可能直接返回思考过程,比如中间步骤或者生成的过程,但有些可能只返回最终结果。需要确认各个模型的API是否支持返回这些信息,如果不行的话可能需要通过prompt设计来让模型返回思考过程。 处理完所有模型的响应后,需要将结果写回Excel。这时候可能需要将每个问题对应的各个模型的回答整理成行,添加到DataFrame中,然后保存回Excel文件。可能需要调整Excel的格式,比如每个模型占一列,思考过程和结果分开存储,或者合并到一个单元格中。 还要考虑异常处理,比如网络请求失败、API限制、响应解析错误等。需要添加try-except块来捕获异常,避免程序中途崩溃,同时记录错误信息,方便后续排查。 另外,可能需要处理异步请求,因为同时调用多个模型的话,串行可能会比较慢。可以使用aiohttp或者concurrent.futures来实现并发请求,提高效率。但如果是同步代码的话,可能更简单,适合初学者。 最后,测试整个流程,确保从读取Excel到调用API再到写回结果都能正确执行。可能需要用示例数据测试,检查每个步骤的输出是否符合预期。 总结下来,步骤大概是:安装依赖库、读取Excel数据、编写各模型API调用函数、循环处理每个问题并调用所有模型、收集响应并保存到DataFrame、写入Excel。同时处理错误和可能的并发请求。</think>以下是使用Python实现Excel与多AI模型交互的完整解决方案: ### 一、实现步骤 1. **环境准备** ```python pip install openpyxl pandas requests # 文心一言需要额外安装ERNIE Bot SDK pip install erniebot ``` 2. **Excel数据结构示例** ```python | 问题ID | 问题内容 | DeepSeek-R11响应 | 文心一言响应 | 腾讯元宝响应 | Kimi响应 | |--------|-------------------|------------------|-------------|--------------|----------| | 001 | 量子计算的原理是? | | | | | ``` 3. **核心代码框架** ```python import pandas as pd from erniebot import ChatCompletion import requests import time def read_excel(file_path): """读取Excel问题列""" return pd.read_excel(file_path) def call_deepseek(question): """调用DeepSeek-R11 API""" headers = {"Authorization": "Bearer YOUR_API_KEY"} payload = { "model": "deepseek-r11", "messages": [{"role": "user", "content": question}], "temperature": 0.7 } response = requests.post("https://api.deepseek.com/v1/chat/completions", json=payload, headers=headers) return response.json()['choices'][0]['message']['content'] def call_erniebot(question): """调用文心一言API""" erniebot.api_type = "aistudio" erniebot.access_token = "YOUR_TOKEN" response = ChatCompletion.create( model="ernie-bot-4", messages=[{"role": "user", "content": question}] ) return response.result def write_to_excel(df, file_path): """将结果写回Excel""" df.to_excel(file_path, index=False) # 主程序 if __name__ == "__main__": df = read_excel("questions.xlsx") for index, row in df.iterrows(): df.at[index, 'DeepSeek-R11响应'] = call_deepseek(row['问题内容']) df.at[index, '文心一言响应'] = call_erniebot(row['问题内容']) time.sleep(1) # 避免API限速 write_to_excel(df, "output.xlsx") ``` ### 二、关键要点 1. **API配置** - 各平台需注册开发者账号获取API密钥 - 腾讯元宝使用`requests`调用REST API,需设置`X-SECURITY-TOKEN`请求头[^1] - Kimi需要构造特定格式的JSON请求体,包含`refs`和`use_search`参数 2. **异步优化** ```python import concurrent.futures def parallel_processing(question): with concurrent.futures.ThreadPoolExecutor() as executor: futures = { "DeepSeek": executor.submit(call_deepseek, question), "文心一言": executor.submit(call_erniebot, question) } return {k: f.result() for k, f in futures.items()} ``` 3. **日志记录** ```python import logging logging.basicConfig(filename='ai_interaction.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') ``` ### 三、注意事项 1. API调用频率限制(如文心一言免费版每分钟3次) 2. 响应内容长度限制(Kimi单次响应最长16k tokens) 3. 错误处理建议: ```python try: response = call_deepseek(question) except requests.exceptions.RequestException as e: logging.error(f"API调用失败: {str(e)}") response = "请求超时" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值