1

I have a dataframe df (it is a time series data) as shown in attached photo. I am able to write this dataframe to the Google Sheet using the code below.

Questions:

  1. In Google Sheet, I would like to draw a horizontal line after each Week ends (shown in photo).
  2. As you can see, I calculate the Year# and Week# (from the Date column). Can the unique combinations of these two columns be used to identify data pertaining to the same week and be used as logic to sketch a line?

Clear the Google Sheet:

service.spreadsheets().values().clear(
    spreadsheetId=spreadsheet_id,
    range='A1:AZ2600',
    body={}
).execute()

Write df_final to Google Sheet:

cell_range_insert= 'B7'
values = df_final.to_json()
body = {'values': values}
response_date= service.spreadsheets().values().append(
    spreadsheetId=spreadsheet_id,
    valueInputOption='RAW',
    range=cell_range_insert,
    body=dict(
        majorDimension= 'ROWS',
        values=df_final.T.reset_index().T.values.tolist()
    )
).execute()

enter image description here

enter image description here

enter image description here

Sinha
  • 431
  • 1
  • 5
  • 12
  • By guessing your situation, I proposed a modified script as an answer. Could you please confirm it? If I misunderstood your question and that was not useful, I apologize. – Tanaike Apr 26 '22 at 08:08
  • 1
    Can you share more details on how you get the data to reproduce it? Also, for the style of the sheet you can check on [Edit cell borders](https://developers.google.com/sheets/api/samples/formatting#edit_cell_borders). – Kessy Apr 26 '22 at 08:25

1 Answers1

1

I believe your goal is as follows.

  • You want to insert the horizontal line every each Week ends to the Spreadsheet.
  • When the script is run, after the script of "Clear the Google Sheet:" was run, the script of "Write df_final to Google Sheet:" is run.
  • The data is put from the cell "B7" in the 1st tab.
  • You want to achieve this using googleapis for python.

In your script, how about the following modified script?

Modified script:

Please set the values of spreadsheet_id and sheet_id.

spreadsheet_id = "###" # Please set Spreadsheet ID.
sheet_id = 0  # Please set the sheet ID.

# 1. Clear sheet. In this case, the values and the horizontal lines are removed.
service.spreadsheets().batchUpdate(
    spreadsheetId=spreadsheet_id, body={"requests": [{
        "repeatCell": {
            "range": {
                "sheetId": sheet_id
            },
            "fields": "userEnteredValue,userEnteredFormat.borders"
        }
    }
    ]}).execute()

# 2. Put the values from the dataframe to Spreadsheet.
cell_range_insert = 'B7'
# values = df_final.to_json() # It seems that this is not used.
# body = {'values': values} # It seems that this is not used.
response_date = service.spreadsheets().values().append(
    spreadsheetId=spreadsheet_id,
    valueInputOption='RAW',
    range=cell_range_insert,
    body=dict(
        majorDimension='ROWS',
        values=df_final.T.reset_index().T.values.tolist()
    )
).execute()

# 3. Set the horizontal lines.
temp = -1
n = []
for index, row in df_final.iloc[:, 5:8].iterrows():
    s = ''.join(row.astype(str).tolist())
    if temp != s:
        n.append(index)
        temp = s
offset = 7
requests = [{
    "repeatCell": {
        "cell": {
            "userEnteredFormat": {
                "borders": {
                    "top": {
                        "style": "SOLID_THICK"
                    }
                }
            }
        },
        "range": {
            "sheetId": sheet_id,
            "startRowIndex": e + offset,
            "endRowIndex": e + 1 + offset,
            "startColumnIndex": 1,
            "endColumnIndex": 10
        },
        "fields": "userEnteredFormat.borders"
    }
} for e in n]
service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body={"requests": requests}).execute()
  • When this script is run, the sheet is cleared using the batchUpdate method. In this case, both the values and the horizontal lines are removed. And, the data is put to the Spreadsheet. And then, the horizontal lines (columns "B" to "J" for every weekend) are put using the batchUpdate method.

  • In order to check the row numbers for putting the border, I used the values of columns "G", "H", "I".

  • In this sample, I used SOLID_THICK as the border. If you want to change this, please change it. Ref

Note:

  • The above script checks the columns "G", "H", "I". If you want to check only the column "I" instead of the columns "G", "H", "I", as a simple modification, please modify the above script as follows.

    • From

        for index, row in df_final.iloc[:, 5:8].iterrows():
      
    • To

        for index, row in df_final.iloc[:, 7:8].iterrows():
      

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • thanks for your code, yes it works. However, at a few instance, the location of the border comes out to be at the wrong location. I have attached photos marked 'Error1' and 'Error2' in the main body. Can we decide to sketch the lines based on only Year# Week# (rather than use Year, Month, Week and Day)? I am wondering if thats the issue since the problem is happening when the Day goes from 30 (or 31) to 1 in the middle of the week. – Sinha Apr 27 '22 at 01:47
  • on a different note, if I want vertical lines around the a combined few columns of the dataframe (just as the vertical line around Y, Mon, Wk, Day columns in the original photo), how to accomplish that? I can create a new question on this if you would like to answer there. – Sinha Apr 27 '22 at 01:50
  • @Sinha Thank you for replying. About `However, at a few instance, the location of the border comes out to be at the wrong location.`, from your initial question, I had thought that you wanted to check columns "G", "H", "I". But from your reply, I understood that you wanted to use only the column "I". This is due to my poor English skill. I deeply apologize for this. For your actual goal, please modify my script from `for index, row in df_final.iloc[:, 5:8].iterrows():` to `for index, row in df_final.iloc[:, 7:8].iterrows():`, and test it again. If this was not useful, I apologize again. – Tanaike Apr 27 '22 at 02:17
  • @Sinha About `on a different note, if I want vertical lines around the a combined few columns of the dataframe (just as the vertical line around Y, Mon, Wk, Day columns in the original photo), how to accomplish that? I can create a new question on this if you would like to answer there.`, I would like to support you. So, I would like to recommend to post it as new question. If you post it as new question, when you include more information, it will help e understand your new question. If you can cooperate to resolve your new question, I'm glad. Can you cooperate to do it? – Tanaike Apr 27 '22 at 02:20
  • here is the link to the post I created just now regarding the vertical line sketching: https://stackoverflow.com/q/72023417/6293211 – Sinha Apr 27 '22 at 04:50
  • @Sinha Thank you for replying. I proposed a sample script by modifying my this sample script as an answer. Could you please confirm it? If that was not useful, I apologize. – Tanaike Apr 27 '22 at 05:42
  • a quick followup to your code you shared: Your code shows how to write the dataframe to Gsheet at the location of cell B7. What if I want to write this data to cell B7 by creating a new sheet (named 'NewSheet') in the same workbook? How would the code need to be modified? – Sinha May 06 '22 at 05:49
  • @Sinha About your new question, I would like to support you. But I have to apologize for my poor English skill. Unfortunately, from `a quick followup` in your comment, I cannot understand what you want to do. So, can you post it as new question by including more information? By this, it will help users including me think of the solution. If you can cooperate to resolve your new issue, I'm glad. Can you cooperate to resolve your new question? – Tanaike May 06 '22 at 05:59
  • as per your request, here is the link to a new question: https://stackoverflow.com/q/72163940/6293211 – Sinha May 08 '22 at 18:19
  • @Sinha Thank you for your response. Now, I noticed that an answer has already been posted. In this case, I would like to respect the existing answer. I think that it will resolve your new question. – Tanaike May 08 '22 at 22:48
  • Hi @Tanaike, thanks for your humble consideration. However, I will suggest please do feel free to write your answer to the question too if you have any better suggestions. After all, always good to have access to the best answer (rather than who answered it first :) ). Your inputs have always been tremendous help for me, thank you. – Sinha May 10 '22 at 04:15
  • @Sinha Thank you for replying. I saw your question and the existing answer. I would like to believe that the answerer will resolve your question. – Tanaike May 10 '22 at 05:20