如何解决如何使用 python 写入 Excel 电子表格??

import xlwt

def output(filename, sheet, list1, list2, x, y, z):
    book = xlwt.Workbook()
    sh = book.add_sheet(sheet)

    variables = [x, y, z]
    x_desc = 'display'
    y_desc = 'Dominance'
    z_desc = 'Test'
    desc = [x_desc, y_desc, z_desc]

    col1_name = 'Stimulus Time'
    col2_name = 'Reaction Time'

    #You may need to group the variables together
    #for n, (v_desc, v) in enumerate(zip(desc, variables)):
    for n, v_desc, v in enumerate(zip(desc, variables)):
        sh.write(n, 0, v_desc)
        sh.write(n, 1, v)

    n+=1

    sh.write(n, 0, col1_name)
    sh.write(n, 1, col2_name)

    for m, e1 in enumerate(list1, n+1):
        sh.write(m, 0, e1)

    for m, e2 in enumerate(list2, n+1):
        sh.write(m, 1, e2)

    book.save(filename)

更多解释: https ://github.com/python-excel

解决方法

我需要将程序中的一些数据写入 Excel
电子表格。我在网上搜索过,似乎有很多可用的软件包(xlwt、XlsXcessive、openpyxl)。其他人建议写入 .csv 文件(从未使用过
CSV,也不真正了解它是什么)。

该程序非常简单。我有两个列表(浮点数)和三个变量(字符串)。我不知道这两个列表的长度,它们可能不会是相同的长度。

我希望布局如下图所示:

布局示例

粉色列将包含第一个列表的值,绿色列将包含第二个列表的值。

那么最好的方法是什么?

我运行的是 Windows 7,但我不一定会在运行此程序的计算机上安装 Office。

import xlwt

x=1
y=2
z=3

list1=[2.34,4.346,4.234]

book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

sheet1.write(0,"Display")
sheet1.write(1,"Dominance")
sheet1.write(2,"Test")

sheet1.write(0,1,x)
sheet1.write(1,y)
sheet1.write(2,z)

sheet1.write(4,"Stimulus Time")
sheet1.write(4,"Reaction Time")

i=4

for n in list1:
    i = i+1
    sheet1.write(i,n)

book.save("trial.xls")

我用你所有的建议写了这篇文章。它完成了工作,但可以稍微改进。

如何将 for 循环(list1值)中创建的单元格格式化为科学或数字?

我不想截断这些值。程序中使用的实际值在小数点后大约有 10 位。