how to combine merge_range and write_formula with xlsxwriter python - 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:

Related

HyperLink Style is not working using set_column in xlsxwriter 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.

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()

Using xlsxwriter to Align Left a Row

xlsxwriter has been pretty powerful and almost everything I want is working, but the following attempt to align left a single row doesn't seem to work.
stats = DataFrame(...)
xl_writer = ExcelWriter(r'U:\temp\test.xlsx')
stats.to_excel(xl_writer, 'Stats')
workbook = xl_writer.book
format_header = workbook.add_format({'align': 'left'})
stats_sheet = xl_writer.sheets['Stats']
stats_sheet.set_row(0, None, format_header)
See the XlsxWriter docs for Formatting of the Dataframe headers:
Pandas writes the dataframe header with a default cell format. Since it is a cell format it cannot be overridden using set_row(). If you wish to use your own format for the headings then the best approach is to turn off the automatic header from Pandas and write your own. For example...

How to write to an Excel sheet without exporting a dataframe first?

I am trying to write some text to a specific sheet in an Excel file. I export a number of pandas dataframes to the other tabs, but in this one I need only some text - basically some comments explaining how the other tabs were calculated.
I have tried this but it doesn't work:
import pandas as pd
writer=pd.ExcelWriter('myfile.xlsx')
writer.sheets['mytab'].write(1,1,'This is a test')
writer.close()
I have tried adding writer.book.add_worksheet('mytab') and
ws=writer.sheets['mytab']
ws.write(1,1,'This is a test')
but in all cases I am getting: keyerror:'mytab'.
The only solution I have found is to write an empty dataframe to the tab before writing my text to the same tab:
emptydf=pd.DataFrame()
emptydf['x']=[None]
emptydf.to_excel(writer,'mytab',header=False, index=False)
I could of course create a workbook instance, as in the example on the documentation of xlsxwriter: http://xlsxwriter.readthedocs.io/worksheet.html
However, my problem is that I already have a pd.ExcelWriter instance, which is used in the rest of my code to create the other excel sheets.
I even tried passing a workbook instance to to_excel(), but it doesn't work:
workbook = xlsxwriter.Workbook('filename.xlsx')
emptydf.to_excel(workbook,'mytab',header=False, index=False)
Is there any alternative to my solution of exporting an empty dataframe - which seems as unpythonic as it can get?
You mentioned that you used add_worksheet() method from the writer.book object, but it seems to work and do what you wanted it to do. Below I've put in a reproducible example that worked successfully.
import pandas as pd
print(pd.__version__)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
ws = workbook.add_worksheet('mytab')
ws.write(1,1,'This is a test')
writer.close()
Thought I'd also mention that I'm using pandas 0.18.1.

Categories