写入 Excel 电子表格 [英] Writing to an Excel spreadsheet

查看:58
本文介绍了写入 Excel 电子表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Python. I need to write some data from my program to a spreadsheet. I've searched online and there seem to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest to write to a .csv file (never used CSV and don't really understand what it is).

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

The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.

我希望布局如下图所示:

I want the layout to be as in the picture below:

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

The pink column will have the values of the first list and the green column will have the values of the second list.

那么最好的方法是什么?

So what's the best way to do this?

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

P.S. I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.

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, 0, "Display")
sheet1.write(1, 0, "Dominance")
sheet1.write(2, 0, "Test")

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

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

i=4

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



book.save("trial.xls")

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

I wrote this using all your suggestions. It gets the job done but it can be slightly improved.

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

How do I format the cells created in the for loop (list1 values) as scientific or number?

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

I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.

推荐答案

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 电子表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆