ExcelWriter align center error when opening output file - python

This code is working well:
excel_path = os.path.join(path,'Report For Yr '+str(date.today().year)+' Mth ' +mth+'.xlsx')
writer = pd.ExcelWriter(excel_path, engine='xlsxwriter')
df2.to_excel(writer, sheet_name='report')
workbook = writer.book
worksheet = writer.sheets['report']
format1 = workbook.add_format({'num_format': '#,###'})
format2 = workbook.add_format({'num_format': '0.00%'})
format3 = workbook.add_format({'num_format': '#,##0.00'})
worksheet.set_column('B:I', 10, format1)
worksheet.set_column('J:J', 10, format2)
worksheet.set_column('L:L', 10, format2)
worksheet.set_column('K:K', 10, format3)
writer.save()
I'm trying to align center for certain columns. The code ran without any error but there is an error when opening the excel file:
Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
I tried with the working code and change this:
format1 = workbook.add_format({'num_format': '#,###'},{'align': 'center'})
got the error message
I tried with the working code and change this:
worksheet.set_column('B:I', 10, format1,{'align': 'center'})
also got the error message
Anyone can help?

I tried with the working code and change this:
That isn't the correct syntax. You should pass a single dict of values. Like this:
format1 = workbook.add_format({'num_format': '#,###', 'align': 'center'})

Related

How to make cell format of 'MMM DD' in xlswriter

I'm stuck in this problem of formatting a cell to date in xlswriter.
The thing is the date is 07/02/2021 and the below image is the result of a manual cell format in excel file which is the correct thing.
While these are the codes I wrote to imitate it.
import xlsxwriter
from datetime import date, datetime
def Test():
workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet()
date_string = "2021-07-02"
datex = datetime.fromisoformat(date_string)
number = datetime.timestamp(datex)
formatx = workbook.add_format({'num_format': 'MMM DD'})
worksheet.write('A1', number, formatx)
workbook.close()
But the result is not even close:
I wanted to imitate a format of 'MMM DD' in excel file that if you look at the 'VALUEs BAR' it is '07/02/2021' and if you look at the 'EXCEL ROW DATA' it is 'July 02'.
But the codes I wrote have the result of these:
'VALUEs BAR': '10/22/ -5025'
'EXCEL ROW DATA': 'Oct 22'
When I clearly set the right date in the variable 'date_string'. How can I do this correctly?
The issue is with the line number = datetime.timestamp(datex), remove it:
import xlsxwriter
from datetime import date, datetime
def Test():
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
date_string = "2021-07-02"
datex = datetime.fromisoformat(date_string)
formatx = workbook.add_format({'num_format': 'MMM DD'})
worksheet.write('A1', datex, formatx)
workbook.close()
Output:

xlsxwriter error: AttributeError: 'Workbook' object has no attribute 'add_format'

I'm doing some simple conditional formatting using xlsxwriter but I am getting this error when I run the code below.
AttributeError: 'Workbook' object has no attribute 'add_format'
I have updated xlsxwriter and looked at a lot of questions on SO and documentation but nothing has worked yet.
This is my code:
workbook = load_workbook(input_excel_filename)
writer = pd.ExcelWriter(input_excel_filename, engine="xlsxwriter")
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
trends_sheet = writer.sheets["Trends"]
slight_increase = writer.book.add_format({"bg_color":"#d3e6d5"})
trends_sheet.conditional_format("E:E", {"type":"cell", "criteria":"==", "value":"Slight Increase", "format":slight_increase})
Check if xlsxwriter package is installed or not....even I faced the same issue..resolved it after installing the package...same answer goes for any attribute error issue related to workbook/writer if your code is correct
Cause and solution
Makesure variable is usable
such as mine
first: workbook = writer.book
then: header_format = workbook.add_format(
Makesure already set pandas's engine (here using xlsxwriter)
when init ExcelWriter, set your engine
writer = pd.ExcelWriter(outputFile, engine='xlsxwriter’, options={'strings_to_urls': False} )
Makesure already installed related lib (xlsxwriter)
pip install xlsxwriter
or mine: pipenv install xlsxwriter
Full code for refer
import pandas as pd
writer = pd.ExcelWriter(
output_final_total_file,
engine='xlsxwriter',
options={'strings_to_urls': False}
)
...
df = pd.read_csv(outputExcelFile, sep=pandas_sep)
...
df.to_excel(outputExcelFile.replace('.csv', '.xlsx'), index=False)
...
df.to_excel(writer, sheet_name=SheetNamePay, startrow=1, header=False, index=False)
...
workbook = writer.book
header_format = workbook.add_format( # !!! here workable, no error
{
'bold': True,
'text_wrap': True,
# 'valign': 'top',
'valign': 'center',
# 'fg_color': '#D7E4BC',
'bg_color': '#edbd93',
'border': 1
}
)
Part of the problem was I needed to set writer.book explicitly. So add the line writer.book = workbook after defining writer. Also adding engine="openpyxl" to the ExcelWriter got rid of a subsequent error. Altogether this seems to work:
workbook = load_workbook(input_excel_filename)
writer = pd.ExcelWriter(input_excel_filename, engine="openpyxl")
writer.book = workbook
writer.sheets = dict((ws.title, ws) for ws in wb.worksheets)
data.to_excel(writer, sheet_name="Data", index=False)
writer.save()
writer.close()
I couldn't get it to work with conditional formatting but setting formatting in the Excel spreadsheet directly actually seems to work, because even if the data is rewritten the formatting stays intact.

Insert Button to Spreadsheet using df.to_excel

I'm trying to insert a button into a spreadsheet, but I'm not able to use insert_button properly.
What I did so far :
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
df_tst.to_excel(writer, sheet_name='Info' ,index = False , header = False)
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()
But I'm not able to use insert_button to the spreasheet " Info " ( probably because I'm trying the wrong way... )
Then I tried a different option that so far it works as expected, but what I'm trying to do is to insert a button just like the following :
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book
worksheet1 = workbook.add_worksheet()
worksheet1.write('A1', 'TEST.')
worksheet1.insert_button('C6', {'macro': 'macro_test',
'caption': 'Macro Test',
'width': 100,
'height': 80})
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()
The problem is that using " worksheet1 = workbook.add_worksheet() ", I'm not able to insert the dataframe to the sheet, giving the following error when I tried :
worksheet1.write(df_tst)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
worksheet1.write(df_tst)
File "C:\Users\...\worksheet.py", line 63, in cell_wrapper
int(first_arg)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DataFrame'
So either inserting the dataframe content into the worksheet created using "workbook.add_worksheet()" or using the "insert_button" to the spreadsheet created by df.to_excel would solve the problem.
Thanks in advance
Here is a working example with Pandas and XlsxWriter. See also Working with Python Pandas and XlsxWriter in the XlsxWriter docs.
import os
import pandas as pd
import xlsxwriter
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('D:D', 30)
# Add the VBA project binary.
workbook.add_vba_project('./vbaProject.bin')
# Show text for the end user.
worksheet.write('D3', 'Press the button to say hello.')
# Add a button tied to a macro in the VBA project.
worksheet.insert_button('D5', {'macro': 'say_hello',
'caption': 'Press Me',
'width': 80,
'height': 30})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
# Pandas doesn't allow a '.xslm' extension but Excel requires
# it for files containing macros so we rename the file.
os.rename('pandas_simple.xlsx', 'pandas_simple.xlsm')
Output:
Try to use xlsxwriter to open directly the file, not pandas wrapper
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet1 = workbook.add_worksheet()
worksheet1.write('A1', 'TEST.')
worksheet1.insert_button('C6', {'macro': 'macro_test',
'caption': 'Macro Test',
'width': 100,
'height': 80})
workbook.add_vba_project(r'C:\Users\...\Project.bin')
workbook.filename = 'test.xlsm'
writer.save()

Change column width of existing tab in excel sheet

I have dataframe (df) that is added to an existing excel file as a new tab ('Print'). I am having difficulties adjusting the column width any ideas?
Code
book = load_workbook('file.xlsx')
writer = pd.ExcelWriter('file.xlsx', engine = 'openpyxl')
writer.book = book
df.to_excel(writer,sheet_name = 'Print')
worksheet = writer.sheets['Print']
worksheet.set_column('B:B', 40) #This does not work
writer = pd.ExcelWriter('file.xlsx', engine='openpyxl')
writer.book = book
df.to_excel(writer, sheet_name='Print')
sheet = book.get_sheet_by_name('Print')
sheet.column_dimensions['B'].width = 40
writer.save()
I've never used nor done this, but I just googled for "worksheet.set_column" and found this:
https://xlsxwriter.readthedocs.io/worksheet.html
The syntax for the function is
set_column(first_col, last_col, width, cell_format, options)
So I'd say the answer is:
worksheet.set_column(2, 2, 40)

How can I iterate over worksheets in win32com?

I generate an xlsx file with lots of sheets and I want to take me at specific position when I open it manually with Excel. This function does the job but for one sheet only. How can I apply it to all of the sheets in workbook?
import win32com.client
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files\1.xlsx')
ws = xl.ActiveSheet
ws.Range('B100').Select()
wb.Close(True)
xl.Quit()
select_cell()
I want to make something like this:
import win32com.client
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files\1.xlsx')
for ws in wb.Worksheets():
ws.Range('B100').Select()
wb.Close(True)
xl.Quit()
select_cell()
In order to be taken to specific cell in newly generated document it is necessary to have both of these expressions executed:
ws.Range('k100').Value = 1
ws.Range('k100').Select()
To do it in every sheet of the workbook:
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files1.xlsx')
for sh in wb.Sheets:
xl.Worksheets(sh.Name).Activate()
ws = xl.ActiveSheet
ws.Range('k100').Value = 1
ws.Range('k100').Select()
wb.Close(True)
xl.Quit()
The code above will take you to K100 on every worksheet in the book.
Your script did nothing at all when I tested it.
The script below worked fine, based on my test.
import xlsxwriter
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:\\Users\\Excel\\Desktop\\book1.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})
# Write some simple text.
worksheet.write('A1', 'Hello')
# Text with formatting.
worksheet.write('A2', 'World', bold)
# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
workbook.close()

Categories