[英]How to save float variables in columns of excel sheet (.xlsx) using python
I am a newbie in Python programming language. 我是Python编程语言的新手。 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.
我的目标是将输出变量(即a,b和c)保存(或写入)在excel文件表(.xlsx格式)中(我尝试了以下python代码),用于写入输出变量。 I want an output excel file (.xlsx) like this: See the image of the excel file .
我想要这样的输出excel文件(.xlsx): 请参阅excel文件的图像 。 The code is working fine with the .csv file, but its not working for .xlsx files
该代码可与.csv文件正常工作,但不适用于.xlsx文件
Following I want to achieve: 以下是我要实现的:
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. Excel文件是二进制格式(从技术上来说是.zip文件),而不是像.csv文件那样的简单文本格式。 If you want to write to a .xlsx file, there are a number of packages that have that capability.
如果要写入.xlsx文件,则有许多具有该功能的软件包。
My preference is for xlsxwriter
. 我的首选是
xlsxwriter
。 It allows you to create a new Excel workbook, write data to it, and add any formatting you want. 它允许您创建一个新的Excel工作簿,向其中写入数据,并添加所需的任何格式。 I am not sure what your for loop was doing, so I modified it so it would work for this example
我不确定您的for循环在做什么,因此我对其进行了修改,使其可以在本示例中使用
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.