如何将Google表格数据写入Microsoft Excel?

swolfe2

底漆:我是非常新的Python的。

我正在获取一些Google表格数据,并使用它创建.xlsx表格。通过下面的代码,我能够让Python读取数据并将其放入数组。但是,我似乎无法弄清楚如何使openpyxl成功地将其写入文档。我假设它与尝试编写数组有关,而不是遍历出现的行。

大家都可以提供的任何帮助/建议将不胜感激。

尝试运行它时收到以下错误:

Traceback (most recent call last):
  File "quickstart.py", line 94, in <module>
    main()
  File "quickstart.py", line 90, in main
    ws.append([values])
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 763, in append
    cell = Cell(self, row=row_idx, col_idx=col_idx, value=content)
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 115, in __init__
    self.value = value
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 299, in value
    self._bind_value(value)
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 206, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert [['Student Name', 'Gender', 'Class Level', 'Home State', 'Major', 'Extracurricular Activity'], ['Alexandra', 'Female', '4. Senior', 'CA', 'English', 'Drama Club'], ['Andrew', 'Male', '1. Freshman', 'SD', 'Math', 'Lacrosse'], ['Anna', 'Female', '1. Freshman', 'NC', 'English', 'Basketball'], ['Becky', 'Female', '2. Sophomore', 'SD', 'Art', 'Baseball'], ['Benjamin', 'Male', '4. Senior', 'WI', 'English', 'Basketball'], ['Carl', 'Male', '3. Junior', 'MD', 'Art', 'Debate'], ['Carrie', 'Female', '3. Junior', 'NE', 'English', 'Track & Field'], ['Dorothy', 'Female', '4. Senior', 'MD', 'Math', 'Lacrosse'], ['Dylan', 'Male', '1. Freshman', 'MA', 'Math', 'Baseball'], ['Edward', 'Male', '3. Junior', 'FL', 'English', 'Drama Club'], ['Ellen', 'Female', '1. Freshman', 'WI', 'Physics', 'Drama Club'], ['Fiona', 'Female', '1. Freshman', 'MA', 'Art', 'Debate'], ['John', 'Male', '3. Junior', 'CA', 'Physics', 'Basketball'], ['Jonathan', 'Male', '2. Sophomore', 'SC', 'Math', 'Debate'], ['Joseph', 'Male', '1. Freshman', 'AK', 'English', 'Drama Club'], ['Josephine', 'Female', '1. Freshman', 'NY', 'Math', 'Debate'], ['Karen', 'Female', '2. Sophomore', 'NH', 'English', 'Basketball'], ['Kevin', 'Male', '2. Sophomore', 'NE', 'Physics', 'Drama Club'], ['Lisa', 'Female', '3. Junior', 'SC', 'Art', 'Lacrosse'], ['Mary', 'Female', '2. Sophomore', 'AK',
'Physics', 'Track & Field'], ['Maureen', 'Female', '1. Freshman', 'CA', 'Physics', 'Basketball'], ['Nick', 'Male', '4. Senior', 'NY', 'Art', 'Baseball'], ['Olivia', 'Female', '4. Senior', 'NC', 'Physics', 'Track & Field'], ['Pamela', 'Female', '3. Junior', 'RI', 'Math', 'Baseball'], ['Patrick', 'Male', '1. Freshman', 'NY', 'Art', 'Lacrosse'], ['Robert', 'Male', '1. Freshman', 'CA', 'English', 'Track & Field'], ['Sean', 'Male', '1. Freshman', 'NH', 'Physics', 'Track & Field'], ['Stacy', 'Female', '1. Freshman', 'NY', 'Math', 'Baseball'], ['Thomas', 'Male', '2. Sophomore', 'RI', 'Art', 'Lacrosse'], ['Will', 'Male', '4. Senior', 'FL', 'Math', 'Debate']] to Excel

这是我到目前为止所做的代码:

from __future__ import print_function
import httplib2
import oauth2client
import os
import googleapiclient
import openpyxl

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from googleapiclient.discovery import build
from openpyxl import Workbook


""" This is the code to get raw data from a specific Google Sheet"""
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret_noemail.json'
APPLICATION_NAME = 'Google Sheets API Python'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run_flow(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


def main():
    """Shows basic usage of the Sheets API.

    Creates a Sheets API service object and prints the names and majors of
    students in a sample spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    rangeName = 'Class Data!A:F'
    result = service.spreadsheets().values().get(
        spreadsheetId=spreadsheetId, range=rangeName).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        wb = Workbook()
        ws = wb.active  
        # Add new row at bottom
        ws.append([values])
        wb.save("users.xlsx")  # Write to disk

if __name__ == '__main__':
    main()

更新:尝试执行ws.append(values)时,出现以下错误:

Traceback (most recent call last):
  File "quickstart.py", line 94, in <module>
    main()
  File "quickstart.py", line 90, in main
    ws.append(values)
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py", line 763, in append
    cell = Cell(self, row=row_idx, col_idx=col_idx, value=content)
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 115, in __init__
    self.value = value
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 299, in value
    self._bind_value(value)
  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\cell\cell.py", line 206, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert ['Student Name', 'Gender', 'Class Level', 'Home State', 'Major', 'Extracurricular Activity'] to Excel

用熊猫码更新:

当索引标记保留为true(未编辑)时,这是数据的布局:

"""
Using pandas and dataframes. For writing large amounts of data, this is probably the best way. 
"""
df=DataFrame(data=values)
df.to_excel('Pandas.xlsx')

索引标记为真

将索引标志标记为false时,数据的外观如下:

"""
Using pandas and dataframes. For writing large amounts of data, this is probably the best way. 
"""
df=DataFrame(data=values)
df.to_excel('Pandas.xlsx', index=False)

索引标志为假

更新2:解决方案!以下来自Zyd和Ben.T的代码完全解决了我的问题。

"""
Using pandas and dataframes. For writing large amounts of data, this is probably the best way. 
"""
df=DataFrame(data=values)
df.to_excel('Pandas.xlsx', header=False, index=False)

没有索引

谢谢大家的帮助!

酵母菌

这可能不正确,但我的回答有点过头,无法发表评论。

您在哪里:

if not values:
    print('No data found.')
else:
    wb = Workbook()
    ws = wb.active  
    # Add new row at bottom
    ws.append([values])
    wb.save("users.xlsx")  # Write to disk

我会尝试

import pandas
if not values:
    print('No data found.')
else:
    dataframe = pandas.DataFrame([values])
    dataframe.to_excel('excel_out.xlsx')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将arrayList中的数据写入多个excel表

如何将数据框写入Excel并更改格式

如何将表格数据从PDF复制到Excel

如何将Excel公式转换为Google表格?

如何使用VBA将Google表格中的数据导入Excel

如何将Python数组写入Excel电子表格

如何将 Python 数组写入单个 Excel 电子表格单元格

如何将数据从SSAS表格模型作为表格导入Excel?

如何将Microsoft Excel Online电子表格链接转换为CSV?

Microsoft Excel和Google表格

如何将Python数据框写入多个Excel文件的多个表

如何将一些数据写入Excel文件(.xlsx)

如何将spark sql数据框的摘要写入excel文件

如何将字符串值的数据帧作为格式数字值写入Excel文件?

如何将mysql表数据写入到excel文件但没有下沉只是存储文件

如何使用Pandas Excel Writer将数据写入Excel文件?

如何将powerpivot数据作为表格复制到excel工作簿中?

如何将 Excel 电子表格导入我的数据库?

Excel:如何将单列混合数据排序到表格中

如何将水平excel数据更改为表格格式

如何将 Excel 电子表格传输到 Access 数据库

如何将Outlook邮件中的数据解析为Excel电子表格

如何将Excel与Google Docs电子表格同步

如何将此数据框写入excel(xlsx)?

如何将Excel数据导入gridview

如何将Matlab结构写入Excel文件?

如何将python字典写入Excel文件?

如何将cpu命令的输出写入excel文件

如何将程序的输出写入Excel工作表