1

I am a newbie in Python programming language. My aim is to save (or write) my output variables i.e a, b and c (as in the following code) in the excel file sheet (.xlsx format) I have tried the following python code, for writing my output variables. I want an output excel file (.xlsx) like this:See the image of the excel file . The code is working fine with the .csv file, but its not working for .xlsx files

Following I want to achieve:

  1. I want to save each variable (a,b,c) in different columns of excel sheet
  2. I want to give names to each columns in excel sheet as (in each columns a, b, c will be stored, and the three columns name should be Value, Cross-range and A-value respectively)

Could anyone please help me on this ? Any suggestions or help regarding this ?

n=10 
for i in range(n-1):
    a[i+1] = a[i]-2
    b=a/10
    c=b**2
    file = open("sample-test.xlsx","w")
    for i in range(len(y)):
    iter = "%.3f,%.3f,%.5f\n"%(a[i],b[i],c[i])
    print (iter)
    file.write(iter)
    file.close()
1

2 Answers 2

2

Excel files are a binary format (technically it is a .zip file), not a simple text format like a .csv file. If you want to write to a .xlsx file, there are a number of packages that have that capability.

My preference is for xlsxwriter. It allows you to create a new Excel workbook, write data to it, and add any formatting you want. I am not sure what your for loop was doing, so I modified it so it would work for this example

import xlsxwriter

wb = xlsxwriter.Workbook('sample-test.xlsx')
ws = wb.add_worksheet('my sheet')

# write the header in row 0, which is Excel row 1
ws.write_row(0, 0, ['chickens', 'ducks', 'mice'])

n = 10
a = 98
for i in range(n-1):
    a = a * i - 2
    b=a/10
    c=b**2
    ws.write_row(i+1, 0, [a,b,c])

wb.close()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your suggestions. If I want to save the variables (say a, b, c) in float format such as %.3f or %.5f, this code will be able to do that ? Could you please provide me your suggestions ?
@Patrick. Same as in Excel you will need to add a number format. In the case of XlsxWriter see the set_num_format() method of the Format object.
0
from openpyxl import Workbook
wb = Workbook() 
# grab the active worksheet
ws = wb.active 
# Data can be assigned directly to cells         
ws['A1'] = 42.2
# Rows can also be append
ws.append([1, 2, 3])

# Save the file
wb.save("sample.xlsx")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.