how write hyperlink to local picture into the cell in openpyxl? - python

I use Python 2.7.3
I need to write hyperlink to local picture into the cell by openpyxl library.
when I need add hyperlink to web site I write something like this:
from openpyxl import Workbook
wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.worksheets[0]
ws.title = 'Name'
hyperlink to local picture
ws.cell('B1').hyperlink = ('http://pythonhosted.org/openpyxl/api.html')
hyperlink to local picture
ws.cell('B2').hyperlink = ('1.png') # It doesn't work!
wb.save(filename = dest_filename)
I have 3 question:
how we can write hyperlink like VBA's style function:
ActiveCell.FormulaR1C1 = _
"=HYPERLINK(""http://stackoverflow.com/questions/ask"",""site"")"
with hyherlink and her name
how we can write hyperlink to local image?
ws.cell('B2').hyperlink = ('1.png') # It doesn't work! And I don't now what to do )
Plese, help me )
Can we use unicode hyperlinks to image? for example when I use
ws.cell('B1').hyperlink =
(u'http://pythonhosted.org/openpyxl/api.html') It fail with error!
for example we have picture 'russian_language_name.png' and we
create hyperlink in exel without any problem. We click to the cell,
and then print
'=Hyperlink("http://stackoverflow.com/questions/ask";"site_by_russian_language")
save document, unzip him. Then we go to him directory to xl->worksheets->sheet1.xml
and we see the title
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
and then ...
row r="2" x14ac:dyDescent="0.25" spans="2:6">-<c r="B2" t="str" s="1"><f>HYPERLINK("http://stackoverflow.com/questions/ask","site_by_russian_language")</f><v>site_by_russian_language</v></c>
everything ok =) Exel supports unicode, but what about python's library openpyxl? It support the unicode in hyperlinks ?

As the files in the .xlsx file are XML files with UTF-8 encoding, Unicode hyperlinks are not a problem.

About Question 2, you need to include the full path of the file link, i think.
If you cannot access the file link in your Excel file, it's the security strategy of Excel that prohibits such actions.

I answered a similar question. Hope this helps.
Well, I could arrive at this. While there is no direct way to build a hyperlink, in your case we could do this way. I was able to build a hyperlink to an existing file using the below code.
wb=openpyxl.Workbook()
s = wb.get_sheet_by_name('Sheet')
s['B4'].value = '=HYPERLINK("C:\\Users\\Manoj.Waghmare\\Desktop\\script.txt", "newfile")'
s['B4'].style = 'Hyperlink'
wb.save('trial.xlsx')
By mentioning the style attribute as 'Hyperlink' is the key. All other code I have may not be of any much importance to you. style attribute would otherwise have a value of 'Normal' Strange thing is even without the style attribute, the hyperlink we working but just that it was lacking style! of course. Though strange, I have seen stranger things. Hope this helps.

Related

How to update Page header using python odfdo module?

I am a complete beginner at python language. For a project I am writing a python script to update a template Open Document File using odfdo module. I am having a hard time with understanding the concept of updating page header. I have looked into Odfdo documentation and found 'get_page_headers' and 'set_page_headers' functions, but have not succeed with its usage.Could someone help me with it?
Thanks
This works for Libreoffice 6.4:
Get the master-page style. With that style loaded, you can just modify the page header.
from odfdo import Document, Style
doc = Document(testdoc)
# its master-page style has the page-header & footer (returns one element list)
mpstyle = doc.get_styles('master-page')[0]
# get the page_header style, you can take a look at the content
print(mpstyle.get_page_header().serialize())
# Now change the page header
mpstyle.set_page_header('New text')
# save your odt file
doc.save(moddoc, pretty=True)
Regards,
Robert

How to put a value to an excel cell?

You'll probably laugh at me, but I am sitting on this for two weeks. I'm using python with pandas.
All I want to do, is to put a calculated value in a pre-existing excel file to a specific cell without changing the rest of the file. That's it.
Openpyxl makes my file unusable (means, I can not open because it's "corrupted" or something) or it plainly delets the whole content of the file. Xlsxwriter cannot read or modify pre-existing files. So it has to be pandas.
And for some reason I can't use worksheet = writer.sheets['Sheet1'], because that leads to an "unhandled exception".
Guys. Help.
I tried a bunch of packages but (for a lot of reasons) I ended up using xlwings. You can do pretty much anything with it in python that you can do in Excel.
Documentation link
So with xlwings you'd have:
import xlwings as xw
# open app_excel
app_excel = xw.App(visible = False)
# open excel template
wbk = xw.Book( r'stuff.xlsx' )
# write to a cell
wbk.sheets['Sheet1'].range('B5').value = 15
# save in the same place with the same name or not
wbk.save()
wbk.save( r'things.xlsx' )
# kill the app_excel
app_excel.kill()
del app_excel
Let me know how it goes.

Insert Image on Worksheet's Header/Footer using OpenPyXL

I'm creating a small app in Django that produces a Excel report using openpyxl library. Got stuck while trying to insert an image in the header / footer section. The documentation here roughly talks about inserting text (& ampersand codes). Checked the source code, but no help there either.
I see XlsxWriter has this option. Would appreciate if someone could shed me light on how to pass image's name/path in openxlpy or do I need to switch the library?
View.py
def get(self, request):
wb = Workbook()
ws = wb.active
# header & footer
ws.header_footer.center_header.text = '&G'
This is currently not possible in openpyxl, and unlikely ever to be so unless someone else contributes the code. Therefore, you may have to switch to using xlsxwriter.
NB. adding it would also involve preserving images from existing files, which is one of the things that makes this so challenging. We open to add general support for reading images in openpyxl 2.5
In openpyxl you can add an image (inserted into some_cell) to a worksheet by doing the following:
wb = openpyxl.Workbook()
ws = wb.add_worksheet() #or wb.active
your_image = openpyxl.drawing.Image(path_to_image)
your_image.anchor(ws.cell(some_cell))
ws.add_image(your_image)
wb.save(your_filename.xlsx)

Python - Excel on Linux - Is there a way to extract comments and hyperlinks?

Is there a way to extract cell comments and hyperlinks from an excel spreadsheet on Linux?
Just tried to get hyperlinks on openpyxl:
c = worksheet.cell('A378')
c.hyperlink
c.value returns the cell value / link text but .hyperlink returns an empty string although a link is there on the spreadsheet...
Perhaps there is another module to do this?
If you're using openpyxl, then presumably you are working with .xlsx files. For now, you probably have to roll your own (meaning you would have to unzip the .xlsx and look around for the relevant pieces yourself; Python does provide tools for these, but at a lower level than openpyxl).
If you can work with .xls instead, then you're in luck: As of version 0.7.2, xlrd will read comments and hyperlinks. Look for the cell_note_map and hyperlink_map sheet properties. (Note that the latest version of xlrd (0.8.0) does read .xlsx files also, but without explicit support for comments or hyperlinks, so would put you in the same boat as openpyxl for now.)
If you are using openpyxl then use the hyperlink attribute of worksheet to get the hyperlink :
wb = load_workbook("file path")
ws= wb['Name of the sheet']
ws.cell(row = rowNumber , column = columnNUmber).hyperlink.target #this will give you the link as output .

Is there any way to edit an existing Excel file using Python preserving formulae?

I am trying to edit several excel files (.xls) without changing the rest of the sheet. The only thing close so far that I've found is the xlrd, xlwt, and xlutils modules. The problem with these is it seems that xlrd evaluates formulae when reading, then puts the answer as the value of the cell. Does anybody know of a way to preserve the formulae so I can then use xlwt to write to the file without losing them? I have most of my experience in Python and CLISP, but could pick up another language pretty quick if they have better support. Thanks for any help you can give!
I had the same problem... And eventually found the next module:
from openpyxl import load_workbook
def Write_Workbook():
wb = load_workbook(path)
ws = wb.get_sheet_by_name("Sheet_name")
c = ws.cell(row = 2, column = 1)
c.value = Some_value
wb.save(path)
==> Doing this, my file got saved preserving all formulas inserted before.
Hope this helps!
I've used the xlwt.Formula function before to be able to get hyperlinks into a cell. I imagine it will also work with other formulas.
Update: Here's a snippet I found in a project I used it in:
link = xlwt.Formula('HYPERLINK("%s";"View Details")' % url)
sheet.write(row, col, link)
As of now, xlrd doesn't read formulas. It's not that it evaluates them, it simply doesn't read them.
For now, your best bet is to programmatically control a running instance of Excel, either via pywin32 or Visual Basic or VBScript (or some other Microsoft-friendly language which has a COM interface). If you can't run Excel, then you may be able to do something analogous with OpenOffice.org instead.
We've just had this problem and the best we can do is to manually re-write the formulas as text, then convert them to proper formulas on output.
So open Excel and replace =SUM(C5:L5) with "=SUM(C5:L5)" including the quotes. If you have a double quote in your formula, replace it with 2 double quotes, as this will escape it, so = "a" & "b" becomes "= ""a"" & ""b"" ")
Then in your Python code, loop over every cell in the source and output sheets and do:
output_sheet.write(row, col, xlwt.ExcelFormula.Formula(source_cell[1:-1]))
We use this SO answer to make a copy of the source sheet to be the output sheet, which even preserves styles, and avoids overwriting the hand written text formulas from above.

Categories