简体   繁体   English

您如何使用 gspread 或其他方式将值从一个电子表格复制到另一个电子表格?

[英]How do you copy values from one spreadsheet to another using gspread or some other way?

(beginner) I'm attempting to copy values from one spreadsheet to another using python. (初学者)我正在尝试使用 python 将值从一个电子表格复制到另一个电子表格。 I'm using gspread but I can't seem to figure out how to copy the values from my first spreadsheet to the other.我正在使用 gspread 但我似乎无法弄清楚如何将值从我的第一个电子表格复制到另一个。 How can I copy values from the first spreadsheet and paste it on the other using python?如何从第一个电子表格中复制值并使用 python 将其粘贴到另一个电子表格上?

Here is the updated code:import gspread这是更新的代码:import gspread

from oauth2client.service_account import ServiceAccountCredentials


scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('sheetproject-956vg2854670.json',scope)
client = gspread.authorize(creds)






spreadsheetId= "1CkeZ8Xw4Xmho-mrFP9teHWVT-unkApzMSUFql5KkrGI"
sourceSheetName = "python test"
destinationSheetName = "python csv"

client = gspread.authorize(creds)
spreadsheet = client.open_by_key(spreadsheetId)
sourceSheetId = spreadsheet.worksheet("python test")._properties['0']. #gid value in the url
destinationSheetId = spreadsheet.worksheet("python csv")._properties['575313690'] #gid value in the url
body = {
    "requests":  [
        {
            "copypaste": {
                "source": {
                    "sheetId": 0,

                    "startRowIndex": 0,
                    "endRowIndex": 20,
                    "startColumnIndex": 0,
                    "endcolumnIndex": 1
                },
                "destination": {
                    "sheetId": 575313690,
                    "startRowIndex": 0,
                    "endRowIndex": 20,
                    "startColumnIndex": 0,
                    "endcolumnIndex": 1
                },
                "pasteType": "Paste_Normal"
            }
        }
    ]
}
res = spreadsheet.batch_update(body)
print(res)
  • You want to copy the values from a sheet to other sheet in a Google Spreadsheet.您想将值从工作表复制到 Google 电子表格中的其他工作表。
  • You want to achieve this using gspread with python.您想使用 gspread 和 python 来实现这一点。
  • You have already been able to get and put values for Google Spreadsheet using Google Sheets API.您已经能够使用 Google Sheets API 获取和放置 Google 电子表格的值。

If my understanding is correct, how about this answer?如果我的理解是正确的,这个答案怎么样? Please think of this as just one of several possible answers.请将此视为几种可能的答案之一。

In this answer, I would like to propose to use batch_update for copying the values from from a sheet to other sheet in the Spreadsheet.在这个答案中,我想建议使用batch_update将值从工作表复制到电子表格中的其他工作表。 In this case, your goal can be achieved by one API call.在这种情况下,您的目标可以通过一个 API 调用来实现。

Sample script:示例脚本:

In this sample script, the script of authorization is removed.在此示例脚本中,删除了授权脚本。 The sample script for copying values from a sheet to other sheet in the Spreadsheet is shown.显示了用于将值从工作表复制到电子表格中的其他工作表的示例脚本。 So when you use this script, please add the authorization script, and run the script.所以当你使用这个脚本时,请添加授权脚本,并运行该脚本。

spreadsheetId = "###"  # Please set the Spreadsheet ID.
sourceSheetName = "Sheet1"  # Please set the sheet name of source sheet.
destinationSheetName = "Sheet2"  # Please set the sheet name of destination sheet.

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(spreadsheetId)
sourceSheetId = spreadsheet.worksheet(sourceSheetName)._properties['sheetId']
destinationSheetId = spreadsheet.worksheet(destinationSheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "copyPaste": {
                "source": {
                    "sheetId": sourceSheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 5,
                    "startColumnIndex": 0,
                    "endColumnIndex": 5
                },
                "destination": {
                    "sheetId": destinationSheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 5,
                    "startColumnIndex": 0,
                    "endColumnIndex": 5
                },
                "pasteType": "PASTE_VALUES"
            }
        }
    ]
}
res = spreadsheet.batch_update(body)
print(res)

Note:笔记:

  • In this sample script, the values of cells of A1:E5 in the sheet of "Sheet1" are copied to the cells of A1:E5 in the sheet of "Sheet2".在此示例脚本中,将“Sheet1”工作表中A1:E5的单元格值复制到“Sheet2”工作表中的A1:E5单元格中。
  • In this case, the range is given by the GridRange .在这种情况下,范围由GridRange给出。
  • This is a simple sample script.这是一个简单的示例脚本。 So please modify this for your actual situation.所以请根据您的实际情况修改它。

References:参考:

If I misunderstood your question and this was not the direction you want, I apologize.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

1) Import openpyxl library as xl. 1) 将 openpyxl 库导入为 xl。

2) Open the source excel file using the path in which it is located. 2)使用它所在的路径打开源excel文件。

Note: The path should be a string and have double backslashes (\\) instead of single backslash ().注意:路径应该是一个字符串并且有双反斜杠 (\\) 而不是单反斜杠 ()。 Eg: Path should be C:\\Users\\Desktop\\source.xlsx Instead of C:\\Users\\Admin\\Desktop\\source.xlsx例如:路径应该是 C:\\Users\\Desktop\\source.xlsx 而不是 C:\\Users\\Admin\\Desktop\\source.xlsx

3) Open the required worksheet to copy using the index of it. 3) 打开需要的工作表,使用它的索引进行复制。 The index of worksheet 'n' is 'n-1'.工作表“n”的索引是“n-1”。 For example, the index of worksheet 1 is 0.例如,工作表 1 的索引为 0。

4) Open the destination excel file and the active worksheet in it. 4) 打开目标 Excel 文件和其中的活动工作表。

5) Calculate the total number of rows and columns in source excel file. 5) 计算源excel文件中的总行数和总列数。

6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable. 6) 使用两个 for 循环(一个用于遍历行,另一个用于遍历 Excel 文件的列)将源文件中的单元格值读取到变量中,然后将其从该变量写入目标文件中的单元格。

7) Save the destination file. 7) 保存目标文件。

here is a py only code example from How to copy over an Excel sheet to another workbook in Python :这是如何将 Excel 工作表复制到 Python 中的另一个工作簿中的仅 py 代码示例:

    import openpyxl as xl

path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.xlsx'

wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]

wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)

for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value

wb2.save(path2)

Using only gspread仅使用 gspread

For copying the whole sheet to another spreadsheet:将整个工作表复制到另一个电子表格:

import gspread

client = gspread.authorize(<put here credentials>)

source_gsheet_url = '<put here url>'
source_worksheet_name = '<put here name>'
dest_gsheet_url = '<put here url>'

ws = gc.open_by_url(source_gsheet_url).worksheet(source_worksheet_name)
ws.copy_to(dest_gsheet_url)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您如何将每月列从一个 dataframe 复制到另一个 - How do you copy monthly columns from one dataframe to another 如何使用 gspread 检索电子表格单元格中的超链接? - how to retrieve hyperlinks in spreadsheet cells using gspread? 将工作表从一个电子表格复制到另一个电子表格 - copy worksheet from one spreadsheet to another Python - GSPREAD - 将文本和格式从一张谷歌表复制到另一张 - Python - GSPREAD - Copy text and format from one google sheet to another one 如何使用 Python xlwings 从一个文件逐个单元格复制到另一个文件 - How do you copy cell by cell with Python xlwings from one file to another 如何使用 gspread lib 从谷歌电子表格中删除/移除行。 在蟒蛇? - How to delete/remove row from the google spreadsheet using gspread lib. in python? 有没有办法用 gspread 或其他一些 Python 库取消合并 Google 表格单元格? - Is there a way to unmerge Google Sheets cells with gspread or some other Python library? 使用gspread无需登录即可读取Google云端硬盘电子表格 - Using gspread to read from a Google Drive Spreadsheet without logging in 从gspread更改电子表格设置 - Change Spreadsheet Settings from gspread 使用 Python 和 openpyxl 将 1 个特定行从一个 Excel 电子表格复制到另一个 - Using Python & openpyxl to copy 1 specific row from one excel spreadsheet to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM