HyperLink Style is not working using set_column in xlsxwriter python - python

I am using python xlsxwriter library to create excel. I need to apply background color to the cell for that I am using set_column method. All columns getting backgroundcolor except the column containing hyperlink. I tried various ways i can try with but not able to found anything. Cell format is working with write_rows but not with set_column containing hyperlink. Can anybody please help.
Sample Code:
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
cell_format = workbook.add_format()
cell_format.set_bg_color('green')
worksheet.write('A1', 'https://google.com')
worksheet.set_column(0, 0, None, cell_format)
workbook.close()
Output:
All columns have green color except having url.

Got the solution for this. There is parameter strings_to_urls which will consider url as string and then bgcolor will get applied.
workbook = Workbook(filename, {'strings_to_urls': False})
We can use this and then we will get bgcolor applied to url as well but it will no more be hyperlink.

Related

How to style a pandas DataFrame into an excel file

I am trying to build an application which writes data into an excel file. I am therefore trying to use the pandas library and I use the xlsxwriter engine. I read the documentation about the Styler object from the pandas library, but I can't find out a way to modify the style of table headers (or column headers, the keys of the dictionary I feed to the DataFrame constructor). In fact, I think the set_table_styles method isn't working very well in my case.
Here is the code I run:
import os
import pandas
writer = pandas.ExcelWriter(f"{os.getcwd()}\\Styled_excel.xlsx", engine="xlsxwriter", mode='w')
data_frame = pandas.DataFrame({"Pressure": [10, 20, 30, 50],
"Volume": [10, 8, 5, 2]})
styler = data_frame.style
styler.set_properties(**{'color': 'red', 'border-color': 'black', 'border-width': "1px"})
styler.set_table_styles([{'selector': 'th', 'props': [('font-weight', 'normal')]}])
styler.to_excel(excel_writer=writer, sheet_name="Feuil1", startrow=4, startcol=2, index=False)
writer.save()
Although the set_properties works as expected, set_table_styles doesn't seem to apply the style I want to, which is a normal font weight for the cells containing "Pressure" and "Volume".
On the same topic, I can't find anywhere in the documentation a way to programmatically change the width of a column, is it just not supported?
If you have any clue on what I might be doing wrong or why it isn't working, I thank you in advance for your answer.
Paul
EDIT: I did find an answer to the issues I had but if someone has an explanation as to why my previous code wasn't working as expected, I'll be glad to hear it (but I think it's due to the fact that the set_table_styles method can only be used when rendering an html page or when displaying the table in Jupyter Notebook)
I found a solution to both my issues on the xlsxwriter documentation (which I didn't know existed before I posted this question):
workbook = writer.book
worksheet = writer.sheets['Feuil1']
# Creation of format for the column headers
header_format = workbook.add_format({
'bold': False,
'border': 1
})
# Writing the column headers only and applying the style with the format created
for col_num, value in enumerate(data_frame.columns.values):
worksheet.write_string(0, col_num, value, header_format)
# Widening a column to fully fit a string in it
worksheet.set_column('C:C', 10)

How to expand Excel cells with new line?

I write a testing Python program, as follow:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet("a")
worksheet.write(0,0, "b\r\nc\r\nd")
workbook.close()
It is expected there will be a cell filled with 3 lines. But when I open it, the three letters are in one line, until I double click the cell like this:
When I download a sheet from doc.google.com, the multiline cells will shrink into one line. After double-click, it will expands.
So, is there any way I can batch expand the cells rather than double click on each one?
The following steps work:
Select all
Click the Wrap Text Button(Home - Alignment - Wrap Text )
Adapt the width of columns and height of rows if necessary.
Thanks to #BruceWayne's question in comment.
Thanks for #Slai's Answer. In a Python script, set_text_wrap() can be used to make same influnce with the action above. The full code:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet("a")
cell_format = workbook.add_format()
cell_format.set_text_wrap()
worksheet.write(0,0, "b\nc\nd", cell_format)
workbook.close()

hyperlink in pandas (dataframe to excel)

I'm trying to create a excel file with url link in a specific column.
Like this
def fill_table(table):
if elapsed_time > datetime.timedelta(minutes=args.mtime):
table.loc[len(table)] = [hostname, int(trigger_id), description, eventStartDate, eventEndDate, elapsed_time, message, useralias, link]
...
writer = pd.ExcelWriter(args.output, engine='xlsxwriter')
I tried to use the excel hyperlink formula in the link variable
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\"; \"{3}\")'.format(args.url, trigger_id,event['eventid'], event['name'])
But I get a error message when open the file and the column 'link' fill with zero's
Probably you need a comma (,) instead of a semi-colon (;) in the formula. This is because Excel stores formulas in US-style syntax (see Non US Excel functions and syntax in the XlsxWriter docs).
When I run your formula through XlsxWriter I get an Excel warning about "We found a problem with some content in 'demo.xlsx'" and when I click on "yes" to recover the formula is zero, as your described.
Changing the semi-colon to a comma makes the program work without warning and as expected:
import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\", \"{3}\")'.format('www.foo.com', 'abc', 'def', 'event1')
worksheet.write('A1', link)
# Or with a hyperlink format.
url_format = workbook.get_default_url_format()
worksheet.write('A2', link, url_format)
workbook.close()
Output:
Use xlwt which has a formula module which will store as a formula object in your dataframe.
You can then write this to excel with pandas using df.to_excel like so:
import xlwt
... # your other code here
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\"; \"{3}\")'.format(args.url, trigger_id,event['eventid'], event['name'])
excel_formatted = xlwt.Formula(link)
Then when this is passed to excel it should appear as the formula of whatever passed. I only tested it with the LEN() function but it worked fine.

Create hyperlink for accessing Multiple excel sheets by python

I have multiple txt files which I am able to merge and write into different excel sheets by the below code:
for file in list(file_lists):
filename = os.path.join(path, file)
df = pd.read_table(filename,sep="|",encoding = "ISO-8859-1")
df.to_excel(writer, sheet_name=file[:-4], index=False,header=True)
writer.save()
I want to now create another sheet (Name = "Homepage") which will contain different sheet names as hyperlinks. I should be able to click on that hyperlink which will take me to the respective sheets. Is there any way I can do that? Any sample codes would be helpful, the similar codes available in SO are not helping me.
This is not really a pandas question, as the pandas.to_excel function has very little to do with the formatting and markup used in the excel sheet.
You can look at xlsxwriter which specifically formats xlsx files.
This is a sample code for formatting hyperlinks, it is adapted from the documentation where you can read more.
###############################################################################
#
# Example of how to use the XlsxWriter module to write hyperlinks
#
# Copyright 2013-2018, John McNamara, jmcnamara#cpan.org
#
import xlsxwriter
# Create a new workbook and add a worksheet
workbook = xlsxwriter.Workbook('hyperlink.xlsx')
worksheet = workbook.add_worksheet('Hyperlinks')
# Format the first column
worksheet.set_column('A:A', 30)
# Add a sample alternative link format.
red_format = workbook.add_format({
'font_color': 'red',
'bold': 1,
'underline': 1,
'font_size': 12,
})
# Write some hyperlinks
worksheet.write_url('A1', 'http://www.python.org/') # Implicit format.
worksheet.write_url('A3', 'http://www.python.org/', string='Python Home')
worksheet.write_url('A5', 'http://www.python.org/', tip='Click here')
worksheet.write_url('A7', 'http://www.python.org/', red_format)
worksheet.write_url('A9', 'mailto:jmcnamara#cpan.org', string='Mail me')
# Write a URL that isn't a hyperlink
worksheet.write_string('A11', 'http://www.python.org/')
workbook.close()

how to combine merge_range and write_formula with xlsxwriter python

this is the code that i'm trying. but its not working.
import xlsxwriter
....
sheet.merge_range.write_formula('F16:H16', """IF('Original data'!B4<>"",'Original data'!B4,"")""", center)
Is there another code that can put both of them become one? i'm already doing some research and don't get any. thanks in advance
From the docs on merge_range():
The merge_range() method writes its data argument using write(). Therefore it will handle numbers, strings and formulas as usual. If this doesn’t handle your data correctly then you can overwrite the first cell with a call to one of the other write_*() methods using the same Format as in the merged cells. See Example: Merging Cells with a Rich String.
Here is a small working example based on yours:
import xlsxwriter
workbook = xlsxwriter.Workbook('example.xlsx')
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet('Original data')
center = workbook.add_format({'align': 'center', 'fg_color': 'yellow'})
worksheet1.merge_range('F16:H16',
"""=IF('Original data'!B4<>"",'Original data'!B4,"")""",
center)
worksheet2.write('B4', 'Hello')
workbook.close()
Output:

Categories