I have work with xlsxwriter and I try to print simple formula with a print of formula into the sheet
import xlsxwriter
workbook = xlsxwriter.Workbook('filename1.xlsx')
format_val=workbook.add_format()
worksheet = workbook.add_worksheet()
worksheet.write(0,1,5)
worksheet.write(1,1,2)
worksheet.write_formula(3,0, '=SUM(B1:B2)')
workbook.close()
csvf = StringIO(import_file.read().decode())
Here the Image of how to show and when I press = than output is print 7
But output also will be Zero (0). I know that XlsxWriter doesn’t calculate the result of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened.
I have tried this. It is working for me but it's not a proper thing when I try with Upper Case is not working: ~
num_formate=format_val.set_num_format('0')
worksheet.write_formula(5,1, '=2+1',num_formate,4)
But when it's open How to show calculate value?
If you use pandas.ExcelWriter with 'xlsxwriter' engine, and .save() it, then it the formula is as you expected. For your case:
import pandas as pd
writer = pd.ExcelWriter('filename1.xlsx', engine='xlsxwriter')
workbook = writer.book
format_val=workbook.add_format()
worksheet = workbook.add_worksheet()
worksheet.write(0,1,5)
worksheet.write(1,1,2)
worksheet.write_formula(3,0, '=SUM(B1:B2)')
writer.save()
However, this write formula in the forth row and first column (A4). If you need to be in the third row and second column (B3), you should use:
worksheet.write_formula(2,1, '=SUM(B1:B2)')
Related
In my project I am opening an Excel file with multiple sheets. I want to manipulate "sheet2" in Python (which works fine) and after that overwrite the old "sheet2" with the new one but KEEP the formatting.. so something like this:
import pandas as pd
update_sheet2 = pd.read_excel(newest_isaac_file, sheet_name='sheet2')
#do stuff with the sheet
with pd.ExcelWriter(filepath, engine='openpyxl', if_sheet_exists='replace', mode='a',
KEEP_FORMATTING = True) as writer:
df.to_excel(writer, sheet_name=sheetname, index=index)
In other words: Is there a way to get the formatting from an existing Excel sheet?
I could not find anything about that. I know I can manually set the formatting in Python but the formatting of the existing sheet is really complicated and has to stay the same.
thanks for your help!
As per your comment, try this code. It will open a file (Sample.xlsx), go to a sheet (Sheet1), insert new row at 15, copy the text and formatting from row 22 and paste it in the empty row (row 15). Code and final screen shot attached.
import openpyxl
from copy import copy
wb=openpyxl.load_workbook('Sample.xlsx') #Load workbook
ws=wb['Sheet1'] #Open sheet
ws.insert_rows(15, 1) #Insert one row at 15 and move everything one row downwards
for row in ws.iter_rows(min_row=22, max_row=22, min_col=1, max_col=ws.max_column): # Read values from row 22
for cell in row:
ws.cell(row=15, column=cell.column).value = cell.value #Update value to row 22 to new row 15
ws.cell(row=15, column=cell.column)._style = copy(cell._style) #Copy formatting
wb.save('Sample.xlsx')
How excel looks after running the code
I am trying to convert the DataFrame to excel without overwriting the existing sheet.
The solution is using pd.ExcelWriter with openpyxl engine which supports append mode.
Now, I have to increase the column size of the excel, I use pd.ExcelWriter with XlsxWriter engine but it overwrites the remaining sheets.
Openpyxl as an engine:
with pd.ExcelWriter("test.xlsx", engine="openpyxl", mode="a") as writer:
df.to_excel(writer, sheet_name="name", startrow=num, startcol=num)
XlsxWriter as an engine:
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 0, 20)
Can someone please suggest to me a solution where I can do both things:
Keep the existing sheets
Increase the column width
you can use your ExcelWriter to adjust the column width. Example below. Note that you can only add a new tab and the data with this, not update text within an existing tab. But, it will NOT delete any contents, like in case of xlsxwriter.
from openpyxl.utils.cell import get_column_letter
startRow = 12 #Change as per your req
startCol = 3 #Change as per your req
with pd.ExcelWriter("test.xlsx", engine="openpyxl", mode="a") as writer: #Your code
df.to_excel(writer, sheet_name="name", startrow=startRow, startcol=startCol) #Your code... mostly
worksheet = writer.sheets['name'] #Get worksheet name
for i, col in enumerate(df.columns): #For each column in df, set width to 60
worksheet.column_dimensions[get_column_letter(startCol+i+1)].width = 60
For my master thesis I've created a script.
Now I want that output to be printed to an excel sheet - I read that xlwt can do that, but examples I've found only give instructions to manually print one string to the file. Now I started by adding that code:
import xlwt
new_workbook = xlwt.Workbook(encoding='utf-8')
new_sheet=new_workbook.add_sheet("1")
Now I have no clue where to go from there, can you please give me a hint? I'm guessing I need to somehow start a loop where each time it writes to a new line for each iteration it takes, but am not sure where to start. I'd really appreciate a hint, thank you!
since you are using pandas you can use to_excel to do that.
The usage is quite simple :
Just create a dataframe with the values you need into your excel sheet and save it as excel sheet :
import pandas as pd
df = pd.DataFrame(data={
'col1':["output1","output2","output3"],
'col2':["output1.1","output2.2","output3.3"]
})
df.to_excel("excel_name.xlsx",sheet_name="sheet_name",index=False)
What you need is openpyxl: https://openpyxl.readthedocs.io/en/stable/
from openpyxl import Workbook
wb = openpyxl.load_workbook('your_template.xlsx')
sheet = wb.active
sheet.cell(row=4, column=2).value = 'what you wish to write'
wb.save('save_file_name.xlsx')
wb.close()
Lets say you would save every result to a list total_distances like
total_distances = []
for c1, c2 in coords:
# here your code
total_distances.append(total_distance)
and than save it into worksheet as:
with Workbook('total_distances.xlsx') as workbook:
worksheet = workbook.add_worksheet()
data = ["Total_distance"]
row = 0
worksheet.write_row(row,0,data)
for i in total_distances:
row += 1
data = [round(i,2)]
worksheet.write_row(row,0,data)
I have an assignment to do for my boring online class and I couldn't come out with an idea to do this thing. I'm told to calculate the ratio of four columns with this formula ratio = weight/heightlengthwidth. Bu i'm bad at using microsoft excel and ironically we haven't learnt anything related to that. So I remembered that there is a python library which works with excel sheets. So how could I calculate this ratio = Weight/HeightWidthLength by using openpyxl for every single row in this excel sheet easily ?
Though I've never used openpyxl library I tried to find a solution to your problem. If the spreadsheet you're working on looks like the one below then you should be able to work with this script.
Sample spreadsheet image
from openpyxl import load_workbook
# Modify filename and sheet name where the data is
workbook_filename = 'workbook.xlsx'
sheet_name = 'Sheet1'
wb = load_workbook(workbook_filename)
ws = wb[sheet_name]
# If the data is stored differently in your file, you have to modify
# this loop to suit your needs
for row in ws.iter_rows(min_row = 2, max_row = 3, max_col = 5):
row[4].value = row[0].value / (row[1].value * row[2].value * row[3].value)
wb.save('result.xlsx')
I would like to format A1:E14 as US Dollars, F1:K14 as percentages and A15:Z1000 as US Dollars. Is there a way to do this in XlsxWriter?
I know how to format full columns as Dollars/Percentages, but I don't know how to format parts of columns -- whatever I do last will overwrite Columns F:K.
Data is starting in pandas so happy to solve the problem there. The following does not seem to work:
sheet.set_column('A1:E14', None, money_format)
More Code:
with pd.ExcelWriter(write_path) as writer:
book = writer.book
money_fmt = book.add_format({'num_format': '$#,##0'})
pct_fmt = book.add_format({'num_format': '0.00%'})
# call func that creates a worksheet named total with no format
df.to_excel(writer, sheet_name='Total', startrow=0)
other_df.to_excel(writer, sheet_name='Total', startrow=15)
writer.sheets['Total'].set_column('A1:E14',20, money_fmt)
writer.sheets['Total'].set_column('F1:K14',20, pct_fmt)
writer.sheets['Total'].set_column('F15:Z1000', 20, money_fmt)
I cannot see a way to achieve per cell formatting using just xlsxwriter with Pandas, but it would be possible to apply the formatting in a separate step using openpyxl as follows:
import openpyxl
def write_format(ws, cell_range, format):
for row in ws[cell_range]:
for cell in row:
cell.number_format = format
sheet_name = "Total"
with pd.ExcelWriter(write_path) as writer:
write_worksheet(df, writer, sheet_name=sheet_name)
wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name(sheet_name)
money_fmt = '$#,##0_-'
pct_fmt = '0.00%'
write_format(ws, 'A1:G1', money_fmt)
write_format(ws, 'A1:E14', money_fmt)
write_format(ws, 'F1:K14', pct_fmt)
write_format(ws, 'F15:Z1000', money_fmt)
wb.save(write_path)
When attempted with xlsxwriter, it always overwrites the existing data from Pandas. But if Pandas is then made to re-write the data, it then overwrites any applied formatting. There does not appear to be any method to apply formatting to an existing cell without overwriting the contents. For example, the write_blank() function states:
This method is used to add formatting to a cell which doesn’t contain
a string or number value.