使用Python将excel数据导出到google工作表

2024-05-03 15:03:31 发布

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

经历了一场灾难, 我需要将位于excel列(“G7”、“G8”)两行中的两个数据导出到google工作表的两列中。我该怎么做

import gspread
from gspread_dataframe import get_as_dataframe, set_with_dataframe
from oauth2client.service_account import ServiceAccountCredentials
import pyperclip
import pyautogui as p
import rpa as r
import pandas as pd
import tabula
import openpyxl

r.init()
r.url('https://www.meudetran.ms.gov.br/veiculo.php#')
p.sleep(2)
janela = p.getActiveWindow()
janela.maximize()
p.sleep(2)

scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_key('1AGYhinoPiE9xUABnrNEfVGjLf5s_bAJGjpz9hatfIQU')
worksheet = wks.get_worksheet(0)
dados = get_as_dataframe(worksheet)
df = pd.DataFrame.from_records(dados, columns=["Placa", "Renavam"])
set_with_dataframe(worksheet, df)
df2 = get_as_dataframe(worksheet)

for row in df2.itertuples():
    df = tabula.read_pdf(text, pages=1)[1]
    df.to_excel('dados.xlsx')
    wb = openpyxl.load_workbook('dados.xlsx')
    sheet = wb.active
    venc = sheet['G8'].value
    valor = sheet['G7'].value
    worksheet.update(row[3], venc)

最后一行不会更新google表单的第3列


Tags: fromimportdataframedfgetasgoogleexcel
1条回答
网友
1楼 · 发布于 2024-05-03 15:03:31

我相信你的目标和现状如下

  • 您希望从PDF数据转换的XLSX数据的第一个选项卡中的单元格“G7”和“G8”中检索值。
    • 你已经做到了这一点
  • 您希望在每次运行脚本时将这些值附加到电子表格中的“C”和“D”列。
    • 例如,在第1次运行时,您希望将检索到的“G7”和“G8”值放入电子表格的单元格“C2”和“D2”。在第二次运行时,您希望将检索到的“G7”和“G8”值放入电子表格的单元格“C3”和“D3”。你想做这个循环
  • 您已经能够使用Sheets API获取和输入Google电子表格的值

修改点:

  • 在脚本中,从电子表格检索的值将转换为数据帧。我想在你的情况下,这可能不是必需的
  • 在这次修改中,我想提出以下流程。
    1. 从PDF数据转换的XLSX数据中检索“G7”和“G8”中的值
    2. 从列“C”和“D”中检索值,并检索列“C”和“D”的最后一行
    3. 将检索到的值附加到Google电子表格中的“C”和“D”列

当上述各点反映到脚本中时,它将变成如下所示

修改的脚本:

在这个修改后的脚本中,我在脚本中修改了以下gc = gspread.authorize(credentials)

gc = gspread.authorize(credentials)
wks = gc.open_by_key('###') # Please set your Spreadsheet ID.
worksheet = wks.get_worksheet(0)

# 1. Retrieve the values from "G7" and "G8" from the XLSX data converted from PDF data.
df = tabula.read_pdf(text, pages=1)[1]
df.to_excel('dados.xlsx')
wb = openpyxl.load_workbook('dados.xlsx')
sheet = wb.active
venc = sheet['G8'].value
valor = sheet['G7'].value

# 2. Retrieve the values from the column "C" and retrieve the last row of the columns "C" and "D".
lastRow = max([len(worksheet.col_values(3)), len(worksheet.col_values(4))])

# 3. Append the retrieved values to the columns "C" and "D" in Google Spreadsheet.
worksheet.update('C' + str(lastRow + 1), [[valor, venc]])
  • 在这个修改过的脚本中,它假设df = tabula.read_pdf(text, pages=1)[1]可以正常工作。请小心这个
  • 通过上述修改,每次运行时检索到的值valor, venc都会附加到列“C”和“D”中

参考文献:

相关问题 更多 >