Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  1. openpyxl seems to change the formula that I insert to a lower case which results in an unknown reference from excel.
  2. 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"
like image 365
Nicholas Smith Avatar asked Aug 14 '13 18:08

Nicholas Smith


People also ask

How do I write a value to a cell in Excel using Python?

There are two basic ways to write to a cell: using a key of a worksheet such as A1 or D3, or using a row and column notation with the cell method. In the example, we write two values to two cells. Here, we assing a numerical value to the A1 cell. In this line, we write to cell B2 with the row and column notation.

What is difference between openpyxl and XlsxWriter?

XlsxWriter vs openpyxl: What are the differences? Developers describe XlsxWriter as "A Python module for creating Excel XLSX files". A Python module for creating Excel XLSX files. On the other hand, openpyxl is detailed as "A Python library to read/write Excel 2010 xlsx/xlsm files".


2 Answers

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' )
like image 123
Brad Avatar answered Oct 11 '22 13:10

Brad


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.

like image 20
ohduran Avatar answered Oct 11 '22 12:10

ohduran