0

我有以下代码:

import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill
import matplotlib
import matplotlib.cm as cm
import numpy as np
import pygsheets
import os

data = [
    [3, 'test', 1],
    [1, 'test', 2],
    [1, 'test', 3],
    [2, 'test', 4],
    [3, 'test', 5],
    [3, 'test', 6],
    [4, 'test', 7],
    [9, 'test', 8]]

write_path = "output2.xlsx"
df = pd.DataFrame(data, columns=["value", "comment", "index"])

with pd.ExcelWriter(write_path) as writer:
    df.to_excel(writer, sheet_name="Sheet1", index=False)

wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name("Sheet1")   

# Create a color map
tohex = lambda r,g,b,a: '%02X%02X%02X%02X' % (a,r,g,b)
tab20c = cm.tab20c(np.linspace(0, 1, 20))
tab20c = np.array(tab20c * 255, dtype=int)
tab20c = iter([tohex(*tab20c[i,:]) for i in range(20)])

colours = {}
next_colour = 'FFFF0000' # start with red

for cells in ws.iter_rows(min_row=2, min_col=1, max_col=1):
    cell = cells[0]

    try:
        colour = colours[cell.value]
    except KeyError:
        colours[cell.value] = next_colour
        colour = next_colour
        next_colour = next(tab20c)    # get the next colour in the colormap

    cell.fill = PatternFill(start_color=colour, end_color=colour, fill_type='solid')

wb.save(write_path) 


#authorization
gc = pygsheets.authorize(service_file='C:/Users/Mikadincic/Google Drive/Python/Jazler Database Project/Jazler Database Project-0e56629e2784.json', no_cache=True)

#open the google spreadsheet (where 'PY to Gsheet Test' is the name of my sheet)
sh = gc.open('Jazler spotovi')

#select the first sheet 
wks = sh[0]

#update the first sheet with df, starting at cell B2. 
wks.set_dataframe(dataframe_spotovi,(1,1))

有没有办法在 Google 表格中做到这一点?对工作表中的更改进行实时预览会好得多,而不必像在写入 xlsx 时那样重新打开文件。

我尝试使用 Google 脚本(自动将驱动器中的 xlsx 转换为表格),但是当您覆盖 xlsx 文件时它不起作用。无论如何,最好直接在 gspread 或 pygsheets 中执行此操作。有什么想法吗?

4

1 回答 1

1

我不确定您在代码中到底在做什么。但是如果你想给单元格上色,在 pygsheets 中(你不能在 gspread 中给单元格上色)你可以使用下面的来给单元格上色

c1 = wks.cell('A1')
c1.color = (1.0,1.0,0.5,1.0) # Red, Green, Blue, Alpha
于 2017-11-19T03:26:14.137 回答