如何在openpyxl中为gsheets中的行着色?

时间:2017-11-19 01:43:06

标签: python google-apps-script gspread pygsheets

我有以下代码:

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在驱动器中转换为Sheets),但是当您只是覆盖xlsx文件时它不起作用。无论如何,最好直接在gspread或pygsheets中这样做。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不确定你在代码中究竟做了什么。但是如果你想要在pygsheets中为单元格着色(你不能在gspread中对单元格进行着色),你可以使用以下方法为单元格着色

c1 = wks.cell('A1')
c1.color = (1.0,1.0,0.5,1.0) # Red, Green, Blue, Alpha