使用xlwtin Python编写列标题

时间:2014-06-23 13:07:45

标签: python excel xlwt

我正在尝试解析一些Twitter Streaming API数据并将特定字段写入Excel工作簿中的列。使用xlwt,我已经能够将列写入Excel文档,但我还没有找到包含列标题的好方法。

我知道什么想让每一列成为第1行中的标签,因此不必从原始数据中解析列名。第1列标题应为" user_screen.name"第2列标题应为" user_lang"

import sys
import json
import xlwt


data = []


for line in open(sys.argv[1]):
    try:
        data.append(json.loads(line))
    except:
        pass

authors = [i['user']['screen_name'] for i in data]
lang = [i['lang'] for i in data]

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet 1')

column_number = 0
for row_number, item in enumerate(authors):
    worksheet.write(row_number, column_number, item)

column_number = 1
for row_number, item in enumerate(lang):
    worksheet.write(row_number, column_number, item)

workbook.save('tweets.xls')

1 个答案:

答案 0 :(得分:1)

如果您只想要静态硬编码标题,只需对程序进行微调(见下文)即可轻松完成此操作:

import sys
import json
import xlwt

data = []

for line in open(sys.argv[1]):
    try:
        data.append(json.loads(line))
    except:
        pass

authors = [i['user']['screen_name'] for i in data]
lang = [i['lang'] for i in data]

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet 1')

column_number = 0
worksheet.write(0, column_number, 'Authors')
for row_number, item in enumerate(authors):
    worksheet.write(row_number+1, column_number, item)

column_number = 1
worksheet.write(0, column_number, 'Language')
for row_number, item in enumerate(lang):
    worksheet.write(row_number+1, column_number, item)

workbook.save('tweets.xls')

注意:如果没有输入文件,我无法完全测试,但我认为这应该可行。