How can I iterate through excel files sheets and insert formula in Python?

2024/10/6 10:33:12

I get this error

TypeError: 'Workbook' object is not subscriptable

when i run this code

import xlsxwriter
from openpyxl import load_workbookin_folder = r'xxx' #Input folder
out_folder = r'xxx' #Output  folderif not os.path.exists(out_folder):os.makedirs(out_folder)file_exist = False  
dir_list = os.listdir(in_folder)
for xlfile in dir_list:if xlfile.endswith('.xlsx') or xlfile.endswith('.xls'):file_exist = Truestr_file = os.path.join(in_folder, xlfile)work_book = xlsxwriter.Workbook(filename=str_file)work_sheet = work_book['test1'] #error above is thrown herework_sheet.write_formula('C2', '=A2+B2') #Add formular but not sure of  how to apply it  to the entire column.out_Path = os.path.join(out_folder,work_book)

Edit: I managed to figure out the above and using this code:-

work_book = openpyxl.load_workbook(os.path.join(in_folder,xlfile)) 
work_sheet = work_book['test1']

However, the issue formulas still exists in the new code below:-

from openpyxl import load_workbookin_folder = r'xxx' #Input folder
out_folder = r'xxx' #Output  folderif not os.path.exists(out_folder):os.makedirs(out_folder)file_exist = False  
dir_list = os.listdir(in_folder)
for xlfile in dir_list:if xlfile.endswith('.xlsx') or xlfile.endswith('.xls'):str_file = xlfile        work_book = openpyxl.load_workbook(os.path.join(in_folder,str_file))work_sheet = work_book['Sheet1']row_count  = work_sheet.max_rowfor row in work_sheet.iter_rows(min_row=1, min_col=1, max_row=work_sheet.max_row):print(row_count)for i, cellObj in enumerate(work_sheet['U'], 2):cellObj.value = f'=Q{row_count}-T{row_count}'work_book.save(os.path.join(out_folder, xlfile))

Ideally, I would like to loop through a folder with .xlsx files, add a formular and apply it to the entire column (U). In this case, I would like to save the files(with the formula effected) in another folder(out_folder).

Answer

Documentation for xlsxwriter.Workbook shows

 work_book.get_worksheet_by_name('test1')

Maybe openpyxl or other module could use ['test1']

https://en.xdnf.cn/q/118968.html

Related Q&A

How to bind all frame widgets to Enter event

I the following code I want to bind all frame1 items to <Enter> Event, but it does not work. I mean canvas.focus_set() does not take effect. How can I solve my problem?for w in frame1.winfo_chil…

Typeerror takes no arguments [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Unable to access element within page

Form Screenshot HTML Inspect Code screenshotIm trying to access an element within a page. Cannot give out the exact page link owing to security concerns. Im writing a python program that uses selenium …

How to wtite Erlang B and Erlang C formulas in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic…

Pip is not recognizing the install command (Windows 7, Python 3.3) [duplicate]

This question already has answers here:python3 --version shows "NameError: name python3 is not defined" [duplicate](2 answers)Closed 6 years ago.I am trying to install Python programs using P…

How do I check if 1 is always followed by a 0

In Python, I cannot find a solution as to how to determine whether there is always a 0 following a 1 somewhere in a list of numbers, to form a pair 10. It doesnt have to be direct follower.For clarity,…

Visual Studio Code debugs even when i run without debugging

i just installed VSCode and I used to work on it but now when I try to run without Debugging with Ctrl + F5. it seems to opens up python debug console and debug like below image enter image description…

Mock global function call while importing

Suppose I have a file called a.py with code likeimport mod1 mod1.a()def b():print("hi")Now if I want to mock fun b() then unittest.py while have import statement at top likefrom a import bat …

can the order of code make this program faster?

Hi this is my first post, I am learning how to write code so technically I am a newbie.I am learning python I am still at the very basics, I was getting to Know the if statement and I tried to mix it …

How can I label a node that is the initial vertex in a cycle from graph data

I need to implement an algorithm such that in a collection of unique and ordered graph edges, I can find a cyclic node. E.g. for a ->b, b->c, c->a, then a is a cyclic node and thus I want to a…