How to use placeholders with openpyxl? - python

I figured it out few weeks ago, but forgot how to do it again.
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for i in range(20):
ws['A{i}'] = 'test'
wb.save('example.xlsx')
How can I replace the i in {i} with the numbers I want to enumerate?

Related

How to add Pandas Dataframe to multiple worksheets starting from FIRST CELL?

I am trying to add Pandas dataframe to all the worksheets in an Excel file.However the starting header index is always becoming B1 wheres I am trying to fit it from A1.
Below is the code:
import os
import xlwt
from xlwt.Workbook import *
from pandas import ExcelWriter
import xlsxwriter
from openpyxl import Workbook, load_workbook
Categories = ["Column" + str(column) for column in range(1,10)]
wb1 = Workbook()
for i in range(1,5):
ws = wb1.create_sheet("1_"+ str(i))
for i in range(5):
ws = wb1.create_sheet("2_"+ str(i))
for i in range(5):
ws = wb1.create_sheet("3_"+ str(i))
for i in range(5):
ws = wb1.create_sheet("4_"+ str(i))
for i in range(5):
ws = wb1.create_sheet("5_"+ str(i))
for i in range(5):
ws = wb1.create_sheet("6_"+ str(i))
wb1.save('FrameFiles.xlsx')
df = pd.DataFrame(columns=Categories)
book = load_workbook('FrameFiles.xlsx')
writer = pd.ExcelWriter('FrameFiles.xlsx',engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
for i in wb1.sheetnames:
df.to_excel(writer, sheet_name=i,index=True,startrow=1,startcol=1)
writer.save()
And the output is coming as following :
enter image description here
I want the header to start from A1 position not B1.I have tried with startrow=0 and startcol=0 also but the result is same. Any suggestion to solve this issue would be highy appreciated.
The empty column is your index column but you have no index in your dataframe so it is empty. try using index=False and you should get what you are expecting
df.to_excel(writer, sheet_name=i,index=False,startrow=0,startcol=0)

Python output not formatting correctly with output to LibreOffice by openpyxl

Attempting to format output to a LibreOffice calc (ie, linux-based Excel) document but the python format syntax isn't applied as expected.
Using the new string formatting, running the below:
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
ws['A3'] = '{:>}'.format('rundate:')
ws['A4'] = '{:>}'.format('name:')
ws['A5'] = '{:>}'.format('comments:')
wb.save('test.xlsx')
Unexpectedly gives this, which appears to be left rather than right aligned:
Trying the left align char on the off chance I had them reversed:
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
ws['A3'] = '{:<}'.format('rundate:')
ws['A4'] = '{:<}'.format('name:')
ws['A5'] = '{:<}'.format('comments:')
wb.save('test.xlsx')
Returns the same:
And another version (specifying total number of chars), makes it clear the text isn't being right aligned. If anything, right aligned text should spill over the left side of the cell, not the right.
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
ws['A3'] = '{:>12}'.format('rundate:')
ws['A4'] = '{:>12}'.format('name:')
ws['A5'] = '{:>12}'.format('comments:')
wb.save('test.xlsx')
From the alignment module:
Alignment options for use in styles.
horizontal
Value must be one of {‘left’, ‘centerContinuous’, ‘center’, ‘distributed’, ‘fill’, ‘justify’, ‘right’, ‘general’}
I think this will work:
from openpyxl.styles import Alignment
alignment=Alignment(horizontal='left')
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
for row in ws.iter_rows(min_col=1, max_col=1, min_row=3, max_row=5):
for cell in row:
cell.alignment = alignment
wb.save('test.xlsx')
or simply:
ws['A3'].alignment = Alignment(horizontal='left')
ws['A4'].alignment = Alignment(horizontal='left')
ws['A5'].alignment = Alignment(horizontal='left')

How to stop openpyxl - python from clearing my excel file every time I re-run the program?

I wrote a simple program for testing with openpyxl where I simply open the .xlsx file, input data into a certain cell, then close the program and run it again, inputting data in a different cell, but when I open the .xlsx after running the program for the second.
My assumption is that openpyxl clears the entire .xlsx file everytime you open it again, is there a way to avoid this?
Here is my code:
from openpyxl import Workbook
wb = Workbook()
dest_filename = 'teste.xlsx'
ws = wb.active
ws.title = "2017"
Row = int(input('row: '))
Column = int(input('column: '))
data = input('data: ')
ws.cell(row = Row, column = Column).value = data
wb.save(filename = dest_filename)
Here is the .xlsx file after running the program for the first time
Here is the .xlsx file after running the program for the second time
You have not read the excel file at all:
Use this to read the existing workbook:
from openpyxl import Workbook,load_workbook
import os
dest_filename = 'teste.xlsx'
if os.path.isfile(dest_filename):
wb = load_workbook(filename = dest_filename)
else:
wb = Workbook()
ws = wb.active
ws.title = "2017"
Row = int(input('row: '))
Column = int(input('column: '))
data = input('data: ')
ws.cell(row = Row, column = Column).value = data
wb.save(filename = dest_filename)
Output:

append rows in Excel using XLWT in Python

How to find total number of rows using XLWT or XLRD in Python? I have an excel file(accounts.xls) and would like to append rows in it.
I am getting an error here - AttributeError: 'Sheet' object has no attribute 'write'
from xlrd import open_workbook
from xlwt import Workbook
def saveWorkSpace(fields,r):
wb = open_workbook('accounts.xls')
ws = wb.sheet_by_index(0)
r = ws.nrows
r += 1
wb = Workbook()
ws.write(r,0,fields['name'])
ws.write(r,1,fields['phone'])
ws.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
Here is the solution of the above question
import xlrd
import xlwt
from xlutils.copy import copy
def saveWorkSpace(fields):
rb = xlrd.open_workbook('accounts.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
r = r_sheet.nrows
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(r,0,fields['name'])
sheet.write(r,1,fields['phone'])
sheet.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
Python Program to add Values to the last data row an Excel sheet.
from xlwt import Workbook
from xlrd import open_workbook
import openpyxl
# Function to get the last RowCount in the Excel sheet , change the index of the sheet accordingly to get desired sheet.
def getDataColumn():
#define the variables
rowCount=0
columnNumber=0
wb = open_workbook('C:\\Temp\\exp\\data.xlsx')
ws = wb.sheet_by_index(0)
rowCount = ws.nrows
rowCount+=1
columnNumber=1
print(rowCount)
writedata(rowCount,columnNumber)
#Data to specified cells.
def writedata(rowNumber,columnNumber):
book = openpyxl.load_workbook('C:\\Temp\\exp\\data.xlsx')
sheet = book.get_sheet_by_name('Sheet1')
sheet.cell(row=rowNumber, column=columnNumber).value = 'Appended Data'
book.save('C:\\Temp\\exp\\data.xlsx')
print('saved')
getDataColumn()
exit()

openpyxl create a function that references a cell in another sheet

I just started working with openpyxl a couple of days ago and its a great library. However, the documentation seems to be sparse for advanced features. I have a couple of issues.
openpyxl seems to change the formula that I insert to a lower case which results in an unknown reference from excel.
furthermore, i changed the name of the sheet to accomidate the lowercase and still found a #NAME? error in the cell where the reference was at.
Can someone please show me how or where to find out how to reference a cell from another sheet in openpyxl
import openpyxl.Workbook
wb = Workbook()
ws = wb.get_active_sheet()
#shows up lowercase with name error in excel
ws.cell('A1).value = "$'Sheet'.E7 + 123"
#still shows a name error in excel
ws.cell('A2').value = "$'sheet'.E7 + 123"
Try this:
from openpyxl import Workbook
wb = Workbook()
ws = wb.create_sheet()
ws.title ='NewSheet'
ws.cell('E7').value = 7
ws = wb.create_sheet()
ws.cell('A1').value = "=NewSheet!E7 + 123"
wb.save( filename = 'temp2.xlsx' )
from openpyxl import Workbook, utils
wb = Workbook()
ws = wb.create_sheet()
ws.title ='NewSheet'
ws.cell('E7').value = 7
ws = wb.create_sheet()
ws.cell('A1').value = f"={utils.quote_sheetname(ws.title)}!E7 + 123"
wb.save( filename = 'temp2.xlsx' )
The problem with the previous answer is that it's dependant on the title of the sheet being 'NewSheet'. Using quote_sheetname()controls that.

Categories

Resources