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.
Related
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?
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 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()
I'm having trouble extracting the styles from an excel worksheet using openpyxl, in the case below I'm creating a spreadsheet, and I can see that the formatting is correct, but I don't know how to get that data back.
In my real use case I'm just reading a file - I'm not the one creating it, so I'd like to be able to programmatically retrieve the formatting.
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
from openpyxl.style import Color, Fill
#this is all setup
wb = Workbook()
dest_filename = 'c:\\temp\\test.xlsx'
ws = wb.worksheets[0]
ws.title = 'test'
ws.cell('A1').value = 'foo'
ws.cell('A1').style.font.bold = True
ws.cell('B1').value = 'bar'
ws.cell('B1').style.fill.fill_type = Fill.FILL_SOLID
ws.cell('B1').style.fill.start_color.index = Color.DARKYELLOW
wb.save(filename = dest_filename )
#setup complete
book = load_workbook( filename = dest_filename )
sheet = book.get_sheet_by_name('test')
#value work properly
print sheet.cell('A1').value #returns foo
print sheet.cell('B1').value #return bar
#formatting does not - THIS IS THE PROBLEM CODE
print sheet.cell('A1').style.font.bold #returns False
print sheet.cell('B1').style.fill.fill_type #returns none
print sheet.cell('B1').style.fill.start_color.index #returns FFFFFFFF
print sheet.cell('B1').has_style #returns true
#but these 2 return the same values! even thought C1 was never set and should be different
print sheet.get_style('A1')
print sheet.get_style('C1')
Is it possible to insert an image (jpeg, png, etc) using openpyxl?
Basically I want to place a generated image with a chart below it.
I don't see anything in the documentation, which seems to be a little lacking compared to the maturity of the code.
The following inserts an image in cell A1. Adjust the image location to your needs or handle the creation of the PIL image yourself and hand that to Image()
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor = 'A1'
ws.add_image(img)
wb.save('out.xlsx')
In older versions of openpyxl the following works:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')
Providing a full update on how to do this. This solution uses openpyxl version 2.4.5.
I downloaded an image to my local directory, opened an existing workbook and saved with the image inserted.
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import coordinate_from_string
openpyxl_version = openpyxl.__version__
print(openpyxl_version) #to see what version I'm running
# downloaded a .png to local directory manually from
# "https://www.python.org/static/opengraph-icon-200x200.png"
#change to the location and name of your image
png_loc = r'c:\users\me\opengraph-icon-200x200.png'
# test.xlsx already exists in my current directory
wb = load_workbook('test.xlsx')
ws = wb.active
my_png = openpyxl.drawing.image.Image(png_loc)
ws.add_image(my_png, 'B3')
wb.save('test.xlsx')
Results:
This code worked for me:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
ws.merge_cells('A1:A3')
img = openpyxl.drawing.image.Image('image.jpg')
row_number = 1
col_idx = 1
cell = ws.cell(row=row_number, column=col_idx)
ws.add_image(img)
wb.save('output.xlsx')
Just to add, I have been using openpyxl==2.5.6 (with Python3.65), and I had to use img.anchor('A1') instead of img.anchor(ws.cell('A1')).
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor('A1')
ws.add_image(img)
wb.save('out.xlsx')