简体   繁体   中英

How to save float variables in columns of excel sheet (.xlsx) using python

I am a newbie in Python programming language. My aim is to save (or write) my output variables ie 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM