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

Export data excel to google sheets with Python

经过迭代, 我需要将位于 excel 列('G7'、'G8')的两行中的两个数据导出到 google sheet 的两列。我该怎么做?

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 sheet

的第 3 列

我认为您的目标和现状如下。

  • 您想从从 PDF 数据转换而来的 XLSX 数据的第一个选项卡的单元格“G7”和“G8”中检索值。
    • 你已经做到了。
  • 您想每隔 运行 脚本将值附加到电子表格中的列“C”和“D”。
    • 例如,在 1st 运行,您想将检索到的“G7”和“G8”值放入电子表格的单元格“C2”和“D2”。并且,在第 2 个 运行,您想将检索到的“G7”和“G8”值放入电子表格的单元格“C3”和“D3”。你想做这个循环。
  • 您已经能够使用表格 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”

参考文献: