Python进入Microsoft Excel

时间:2016-01-10 16:44:53

标签: python excel

我是python的新手,我需要从python中获取一些信息和数据到excel文档中。

import csv
class_name = input("What class are you in?")
name = input("Name")

score = 0
print ("What's 1 + 2")
answer = int(input("What's the correct answer?"))
if answer == 3:
   print("Congratulations!")
   score = score + 1
else:
   print("Wrong answer")

if class_name == ('1'):
scoreRecords.append([name,score])
csvfile = open('Class.1 records.csv','a',newline='')
scoreWriter = csv.writer(csvfile)
scoreWriter.writerows(coreResults)
csvfile.close()    

我需要将上面列出的两个变量放到excel文档中,并将它们作为标题,名称和class_names需要在相应的列下面连续添加。然而,没有任何事情发生,错误即将来临。

这个问题现在已经得到解答,但是对于其他任何想要学习如何做到这一点的人来说,基本上我想使用import csv函数,将三个变量从python测验移到excel文档上变量名称位于顶部,相应的值输出正确的变量名称。希望现在已经清除了任何混乱。

2 个答案:

答案 0 :(得分:0)

如果您希望生成本机xlsx文件,则需要安装合适的Excel模块。如果您选择使用openpyxl创建xlsx文件,以下内容可帮助您入门:

from openpyxl import Workbook

class_name = raw_input("What class are you in? ")
name = raw_input("Name ")

wb = Workbook()
ws = wb.active

ws.cell(row=1, column=1, value="Class name")
ws.cell(row=1, column=2, value="Name")

ws.cell(row=2, column=1, value=class_name)
ws.cell(row=2, column=2, value=name)

wb.save("output.xlsx")

这将为您提供以下内容:

Excel output example

这是使用Python 2.7.9

测试的

根据您更新的问题,希望以下内容对您有所帮助。你似乎开始开展某种测验,因此你需要花一些时间来研究你想问的问题。

有一点需要注意,在处理文件时使用Python的with语句会更容易,这将自动确保在结束时调用close

import csv
import os

with open('Class.1 records.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)

    # Write the csv header row
    csv_output.writerow(['Class name', 'Name', 'Score'])

    score = 0

    while True:
        class_name = input("What class are you in? (Or type q to quit) ")

        if class_name == 'q':
            break

        name = input("Name: ")

        print ("What's 1 + 2")
        answer = int(input("What's the correct answer? "))

        if answer == 3:
            print("Congratulations!")
            score = score + 1
        else:
            print("Wrong answer")

        csv_output.writerow([class_name, name, score])

因此脚本的工作原理如下:

What class are you in? (Or type q to quit) 9
Name: Fred
What's 1 + 2
What's the correct answer? 0
Wrong answer
What class are you in? (Or type q to quit) 8
Name: Wilma
What's 1 + 2
What's the correct answer? 3
Congratulations!
What class are you in? (Or type q to quit) q

为您提供以下CSV文件内容:

Class name,Name,Score
9,Fred,0
8,Wilma,1

使用Python 3.4.3进行测试

答案 1 :(得分:0)

我只能猜测,您看到了哪些错误,但第一个可能的问题是if class_name == ('1')条款中的缩进缩进。

第二:您尝试追加到scoreRecords,但scoreRecords未定义。

第三:在writerow上使用scoreWriter方法将namescore变量列表写入文件。