I have an optimization problem that runs in a for loop. I want the results of each new iteration to be saved in a different tab in the same workbook.
This is what I'm doing. Instead of giving me multiple tabs in the same workbook, I'm getting multiple workbooks.
from openpyxl import Workbook
wb1 = Workbook()
for i in range(n):
ws = wb1.active()
ws.title = str(i)
#code on formatting sheet, optimization problem
wb1.save('outfile'+str(i)+'.xlsx')
Every iteration you are grabbing the same worksheet - ws = wb1.active() - and then simply saving your results to a different workbook.
You simply need to create a new sheet on each iteration. Something like this:
from openpyxl import Workbook
wb1 = Workbook()
for i in range(n):
ws = wb1.create_sheet("run " + str(i))
#code on formatting sheet, optimization problem
wb1.save('outfile.xlsx')
Notice that the save is indented out to simply save the file once all worksheets have been formatted. It is not necessary to save on each iteration. The saving operation can take time, especially when adding more tabs.
This code will create Excel Workbook containing worksheets same as the number of strings in a text file taken as the input. Here i have a text file named 'sample.txt' having 3strings. This code will so create 3 worksheets in a workbook named 'reformatted.data.xls'.
Also i have removed the default worksheets that get created automatically when the workbook object is created.
import xlwt
from openpyxl import Workbook
wb1 = Workbook()
row = 0
f = open('C:\Desktop\Mytestcases\sample.txt')
lines = f.readlines()
for i in range(len(lines)):
ws = wb1.create_sheet("worksheet" + str(i))
ws.cell(row=1, column=1).value = lines[i]
row += 1
sheet = wb1.get_sheet_by_name('Sheet')
wb1.remove_sheet(sheet)
wb1.save('reformatted.data.xls')
Related
I have one big excel,including several sheets. Now I need to save every sheet in one excel. Now, I finish and some cells which have formulas have value in the new excel. But I find one new problem,how can I save every sheets which keeps the original style (format) such as red background?I checked the former question, but still get no answer. Editing workbooks with rich text in openpyxl
from openpyxl import load_workbook,Workbook
wb = load_workbook("test11.xlsx",data_only=True)
sheetnames = wb.sheetnames
for name in sheetnames:
ws = wb.get_sheet_by_name(name)
print(ws)
wb2 = Workbook()
ws2 = wb2.active
for i,row in enumerate(ws.iter_rows()):
for j,cell in enumerate(row):
ws2.cell(row=i+1, column=j+1, value=cell.value)
ws2.title = name
wb2.save(name + ".xlsx")
Every cell in openpyxl has a .style attribute that you can call and set. Your code would be this:
from openpyxl import load_workbook,Workbook
wb = load_workbook("test11.xlsx",data_only=True)
sheetnames = wb.sheetnames
for name in sheetnames:
ws = wb.get_sheet_by_name(name)
print(ws)
wb2 = Workbook()
ws2 = wb2.active
for i,row in enumerate(ws.iter_rows()):
for j,cell in enumerate(row):
c = ws2.cell(row=i+1, column=j+1, value=cell.value)
c.style = cell.style
ws2.title = name
wb2.save(name + ".xlsx")
You could consider the following option instead.
Basically this code makes a copy of the original xlsx file and deletes the unwanted sheets before saving with the sheet name. Since it is a copy of the original it should retain all the styling etc of each sheet.
from openpyxl import load_workbook
sheetnames = load_workbook('test11.xlsx').sheetnames
for name in sheetnames:
wb = load_workbook("test11.xlsx")
print(wb[name])
for delsheet in sheetnames:
if delsheet != name:
del wb[delsheet]
wb.calculation.calcMode = 'auto' # set formula calculation to auto
wb.save(name + ".xlsx")
openpyxl creates spreadsheet with name "Sheet1" by default
even though I'm specifying that the sheet should be created with index 0.
I'm sure it's not a duplicate question.
Documentation says openpyxl supports 2010 MS Office version but I'm using office365 pro.
Could you provide any help or suggestions?
Please note that standalone code is working fine for me but when the same code is being integrated with other code I experience the problem described below.
I have tried many things. Since I'm new to Python it looks like there's something I'm not aware of.
If I specify index 1 there are two worksheets created: one with name Sheet and the other one with name I'm providing. If I provide Index 0 there is only one Sheet with name Sheet1 created.
The code below should create worksheet at index 0 with name test.
for r in range(3, rowcount + 1):
for c in range(1, columncount + 1):
final_path = first_part + str(r) + second_part + str(c) + third_part
table_data = self.driver.find_element_by_xpath(final_path).text
fname = r"{}_{}.xlsx".format(str(i[1]), str(i[2]))
if (os.path.exists(fname)):
workbook = openpyxl.load_workbook(fname)
worksheet = workbook[fname]
else:
workbook = Workbook()
worksheet= workbook.create_sheet(fname,0)
#worksheet = workbook.active
#worksheet.title = fname
worksheet.cell(row=r,column=c).value = table_data
workbook.save(fname)
openpyxl creates a single sheet called "Sheet" when you first call the Workbook() function. It's just a kind of annoying quirk of the module.. The cleanest way I found to deal with it is to just rename that sheet instead of attempting to make a new one
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
wb.save("Test.xlsx")
Will create an xlsx file with a single worksheet called "My sheet name".
When you call create_sheet with index 0, you just insert a new sheet before this original sheet.
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "My sheet name"
ws2 = wb.create_sheet("Another Name", 0)
wb.save("Test.xlsx")
Will create an xlsx where the first sheet is called "Another name" and the second sheet is called "My sheet name". If you're dealing with one sheet workbooks it's easiest to just use title.
You can remove this sheet via:
from openpyxl import Workbook
workbook = Workbook()
del workbook['Sheet']
You can get that sheet and remove like this :
sheet = wb1.get_sheet_by_name('Sheet')
wb1.remove_sheet(sheet)
I am finding a way to split an Excel workbook, contains multiple tabs/sheets, into multiple workbooks, according to the numbers of tabs/sheets the original workbook has:
Worked out:
from xlrd import open_workbook
from xlwt import Workbook
rb = open_workbook('c:\\original file.xls',formatting_info=True)
for a in range(5): #for example there're only 5 tabs/sheets
rs = rb.sheet_by_index(a)
new_book = Workbook()
new_sheet = new_book.add_sheet('Sheet 1')
for row in range(rs.nrows):
for col in range(rs.ncols):
new_sheet.write(row, col, rs.cell(row, col).value)
new_book.save("c:\\" + str(a) + ".xls")
This is actually nothing but reading the sheets one by one, and save them one by one. Is there a better, or more direct way?
I have to create and write a new excel workbook with about 5 worksheets. The purpose of my code is to read a database and split that into different sheets depending on certain criterion.
I have used the following code in python 2.7 using openpyxl-1.1.0
from openpyxl.workbook import Workbook
dest_filename = 'D:\\Splitted.xlsx'
wb = Workbook()
ws1 = wb.worksheets[0]
ws1.title = 'Criterion1'
ws2 = wb.worksheets[1]
ws2.title = 'Criterion2'
## Read Database, get criterion
if criterion == Criterion1:
ws1.cell('A1').value = 'A1'
ws1.cell('B1').value = 'B1'
elif criterion == Criterion2:
ws2.cell('A1').value = 'A2'
ws2.cell('B1').value = 'B2'
wb.save(filename = dest_filename)
I am able to write single sheet, but if I try to create 2nd worksheet, I am getting an error saying "Index out of range" at code
ws2 = wb.worksheets[1]
Is there any solution to write 2 or more worksheets in a single workbook at the same time?
You shouldn't try and access worksheets by index. The error is because the second worksheet hasn't been created (every workbook has a single worksheet created automatically).
ws1 = wb.active
ws2 = wb.create_sheet()
Should solve your problem.
I need to change the sheet in an excel workbook, as many times as the code runs..Suppose my python scripts runs the first time and data gets saved in sheet A, next time when some application runs my script data should be saved in sheet B.Sheet A should be as it is in that workbook..
Is it posible ? If yes ,How?
Here is my code:
#!/usr/bin/env python
import subprocess
import xlwt
process=subprocess.Popen('Test_Project.exe',stdout=subprocess.PIPE)
out,err = process.communicate()
wb=xlwt.Workbook()
sheet=wb.add_sheet('Sheet_A') #next time it should save in Sheet_B
row = 0
for line in out.split('\n'):
for i,wrd in enumerate(line.split()):
if not wrd.startswith("***"):
print wrd
sheet.write(row,i,wrd)
row=row+1
wb.save('DDS.xls')
Any help is appreciated...
I would recommend using openpyxl. It can read and write xlsx files.
If needed, you can always convert them to xls with Excel or Open/LibreOffice,
assuming you have only one big file at the end.
This script creates a new Excel file if none exists and adds a new sheet every time it is run. I use the index + 1 as the sheet name (title) starting with 1. The numerical index starts at 0. You will end up with a file that has sheets named 1, 2, 3 etc. Every time you write your data into the last sheet.
import os
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
file_name = 'test.xlsx'
if os.path.exists(file_name):
wb = load_workbook(file_name)
last_sheet = wb.worksheets[-1]
index = int(last_sheet.title)
ws = wb.create_sheet(index)
ws.title = str(index + 1)
else:
wb = Workbook()
ws = wb.worksheets[0]
ws.title = '1'
ws.cell('A2').value= 'new_value'
wb.save(file_name)