it seems that I can't update the sheet (worksheet) name,
what to do?
sh = gc.open('My worksheet')
worksheet = sh.get_worksheet(0)
worksheet.update_title = 'my sheet'
Please take a look at the documentation. You can see that update_title is supposed to be a function call which you call as shown below.
worksheet.update_title('my sheet')
Related
everyone. I'm looking for a way to make notes in excel worksheet, using python. Found a way to add comments, but I need notes like on screenshot. Is there an easy way to add them using openpyxl or any other lib? screenshot of a note
Updating this because this post is the top google result
The openpyxl docs incorrectly refer to notes as comments. Just follow the instructions in the docs on how to add comments: https://openpyxl.readthedocs.io/en/latest/comments.html. There is one issue with their example code though in the docs, so use the below code instead:
from openpyxl import Workbook
from openpyxl.comments import Comment
wb = Workbook()
ws = wb.active
comment = Comment('This is the comment text', 'Comment Author')
ws["A1".comment] = comment
wb.save('your_file.xlsx')
I've been trying to accomplish the same thing. Apparently that "note" is the same as data validation as described in the docs.
So what you do is:
from openpyxl import load_workbook
from openpyxl.worksheet.datavalidation import DataValidation
wb = load_workbook('my_sheets.xlsx')
# Create 'note'
dv = DataValidation()
dv.errorTitle = 'Your note title'
dv.error = 'Your note body'
# Add 'note' to A1 in the active sheet
dv.add(wb.active['A1'])
# This is required also, or you won't see the note
wb.active.add_data_validation(dv)
wb.save('my_sheet_with_note.xlsx')
It also mentions prompts, which is something you can look into:
# Optionally set a custom prompt message
dv.promptTitle = 'List Selection'
dv.prompt = 'Please select from the list'
Edit: I updated the answer with a part of the code that solved my problem at the time:
def add_note(cell, prompt_title='', prompt=''):
p = {
'promptTitle': prompt_title[:32],
'prompt': prompt[:255],
}
dv = DataValidation(**p)
dv.add(cell)
cell.parent.add_data_validation(dv)
Ok I'm new to python but...I really like it. I have been trying to figure this out for awhile and thought someone could help that knows a lot more than I.
So what I would like to do is use pygsheets and combine batch the updates with one api call vs several. I have been searching for examples or ideas and found if you unlink and link it will do this? I tried and it speed it up only a little bit, then I looked and you could use update.values vs update.value. I have got it to work with the something like this wk1.update_values('A2:C4',[[1,2,3],[4,5,6],[7,8,9]]) but what if you want the updates to be in specific cell locations vs a range like a2:c4? I appreciate any advice in advance.
https://pygsheets.readthedocs.io/en/latest/worksheet.html#pygsheets.Worksheet.update_values
https://pygsheets.readthedocs.io/en/latest/sheet_api.html?highlight=batch_updates#pygsheets.sheet.SheetAPIWrapper.values_batch_update
import pygsheets
gc = pygsheets.authorize() # This will create a link to authorize
# Open spreadsheet
GS_ID = ''
File_Tab_Name = 'File1'
Main_Topic = 'Main Topic'
Actual_Company_Name = 'Company Name'
Street = 'Street Address'
City_State_Zip = 'City State Zip'
Phone_Number = 'Phone Number'
# 2. Open spreadsheet by key
sh = gc.open_by_key(GS_ID)
sh.title = File_Tab_Name
wk1 = sh[0]
wk1.title = File_Tab_Name
#wk1.update_values('A2:C4',[[1,2,3],[4,5,6],[7,8,9]])
wk1.update_values([['a1'],['h1'],['i3']],[[Main_Topic],[Actual_Company_Name],[Street]]) ### is this possible
#wk1.unlink()
#wk1.title = File_Tab_Name
#wk1.update_value("a1",Main_Topic) ###Topic
#wk1.update_value("h1",Actual_Company_Name) ###Company Name
#wk1.update_value("i3",Street) ###Street Address
#wk1.update_value("i4",City_State_Zip) ###City State Zip
#wk1.update_value("i5",Phone_Number) ### Phone Number
#wk1.link() # will do all the updates
From what I could undersand you want to batch update values. you can use the update_values_batch function.
wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1],[2]], [[3],[4]]])
# or
wks.update_values_batch([((1,1), (2,1)), 'B1:B2'], [[[1,2]], [[3,4]]], 'COLUMNS')
# or
wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1,2]], [[3,4]]], 'COLUMNS')
see doc here.
NB: update pygsheets to latest version or install from gitub
pip install --upgrade https://github.com/nithinmurali/pygsheets/archive/staging.zip
Unfortunately, pygsheets has no method for updating multiple ranges in batch. Instead, you can use gspread.
gspread has batch_update method where you can update multiple cell or range at once.
Example:
Code:
import gspread
gc = gspread.service_account()
sh = gc.open_by_key("insert spreadsheet key here").sheet1
sh.batch_update([{
'range': 'A1:B1',
'values': [['42', '43']],
}, {
'range': 'A2:B2',
'values': [['44', '45']],
}])
Output:
References:
gspread:batch_update()
gspread Authentication
I am writing a telegram bot, where I want to store the information that the user will input in a excel spreadsheet. Two libraries the I am using are teleport and openpyxl. I am facing a problem that data is not writing in excel file.
Here is my code:
import telebot
import openpyxl
bot = telebot.TeleBot("TOKEN")
wb = openpyxl.load_workbook('results.xlsx')
ws = wb['Poll']
last_row = ws.max_row + 1
#bot.message_handler(content_types=['text'])
def handle_text(message):
if message.text == '/start':
bot.send_message(message.from_user.id, 'Hello Welcome')
user_id = str(message.from_user.id)
ws.cell(row = last_row, column = 1).value = user_id #here is where the problem is
wb.save('results.xlsx')
bot.polling(none_stop=True, timeout=60)
The code is not giving any mistakes, moreover, if I put ws.cell line before #bot.message_handle and give some value it works. It is just not working inside the decorator. Does anyone know how to fix this problem?
Thanks!
Your code currently has a fixed value for the row where you write data so you will always overwrite the same cells. Much better simply to append to the worksheet:
ws.append([user_id])
I am looking to setup a macro in Google Sheets and I am having issues. Below is my script:
function clearRange() {
//replace 'Sheet1'
var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
sheet1.getRange('D3:D46').clearContent();
}
Below is the error I am getting:
TypeError: Cannot call method "getRange" of null. (line 4, file
"Code")
Can any review this and let me know what I am not seeing here.
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
found here
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getSheetByName(String)
This code fails with error: "AutoFilter method of Range class failed"
from win32com.client.gencache import EnsureDispatch
excel = EnsureDispatch('Excel.Application')
excel.Visible = 1
workbook = excel.Workbooks.Add()
sheet = workbook.ActiveSheet
sheet.Cells(1, 1).Value = 'Hello world'
sheet.Columns.AutoFilter()
This code also fails although it used to work:
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
excel.Visible = 1
workbook = excel.Workbooks.Add()
sheet = excel.ActiveSheet
sheet.Cells(1, 1).Value = 'Hello world'
sheet.Columns.AutoFilter()
Python uses win32com to communicate directly with Windows applications, and can work with (via EnsureDispatch) or without (via Dispatch) prior knowledge of the application's API. When you call EnsureDispatch, the API is fetched and written into win32com.gen_py., thereby permanently adding the application's API into your Python library.
Once you've initialised an application with EnsureDispatch, any time that a script uses Dispatch for that application, it will be given the pre-fetched API. This is good, because you can then make use of the predefined application constants (from win32com.client import constants).
However, sometimes previously working code will break. For example, in the following code, AutoFilter() will work without an argument as long as the Excel API has never previously been cached in the library...
# ExcelAutoFilterTest1
# Works unless you ever previously called EnsureDispatch('Excel.Application')
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
excel.Visible = 1
workbook = excel.Workbooks.Add()
sheet = workbook.ActiveSheet
sheet.Cells(1, 1).Value = 'Hello world'
sheet.Columns.AutoFilter()
The following code will always fail because now the Excel API has been fetched and written to win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x7 in your Python library, it will no longer accept AutoFilter() without an argument.
# ExcelAutoFilterTest2
# Always fails with error: AutoFilter method of Range class failed
from win32com.client.gencache import EnsureDispatch
excel = EnsureDispatch('Excel.Application')
excel.Visible = 1
workbook = excel.Workbooks.Add()
sheet = workbook.ActiveSheet
sheet.Cells(1, 1).Value = 'Hello world'
sheet.Columns.AutoFilter()
The following code always works because we're now providing the VisibleDropDown argument (1=on, 0=off).
# ExcelAutoFilterTest3
# Always succeeds
from win32com.client.gencache import EnsureDispatch
excel = EnsureDispatch('Excel.Application')
excel.Visible = 1
workbook = excel.Workbooks.Add()
sheet = workbook.ActiveSheet
sheet.Cells(1, 1).Value = 'Hello world'
sheet.Columns.AutoFilter(1)
This seems to be a bug, because the Excel API documentation claims that all arguments to AutoFilter are optional:
"If you omit all the arguments, this method simply toggles the display
of the AutoFilter drop-down arrows in the specified range."