如何在python字典键中创建excel的头文件

时间:2017-07-19 21:24:56

标签: python excel dictionary header

我正在尝试在python中获取一个字典并将其放入一个excel工作表中,其中的键显示在工作表的标题部分中,值将在列中。我很接近我只是遗漏了一些小东西,无法弄清楚这里是我的代码。注意我使用许多导入方法

import os
import re
import openpyxl
from openpyxl.utils import get_column_letter, column_index_from_string
import xlsxwriter
import pprint
from openpyxl.workbook import Workbook
from openpyxl.worksheet.copier import WorksheetCopy


workbook = xlsxwriter.Workbook('dicExcel.xlsx')
worksheet = workbook.add_worksheet()

d = {'a':['Alpha','Bata','Gamma'], 'b':['1','2','3'], 'c':['1.0','2.0','3.0']}
row = 0
col = 1

for key in d.keys():
row += 1
worksheet.write(row, col, key)
for item in d[key]:
    worksheet.write(row, col + 1, item)
    row += 1

workbook.close()

2 个答案:

答案 0 :(得分:1)

我认为这就是你要做的事情:

import xlsxwriter

workbook = xlsxwriter.Workbook('dicExcel.xlsx')
worksheet = workbook.add_worksheet()

d = {'a':['Alpha','Bata','Gamma'], 'b':['1','2','3'], 'c':['1.0','2.0','3.0']}
row = 0
col = 0

for key in d.keys():
    row = 0
    worksheet.write(row, col, key)
    row += 1
    for item in d[key]:
        worksheet.write(row, col, item)
        row += 1
    col += 1

workbook.close()

这会将数据放入以下格式:

a       c      b
Alpha   1.0    1
Bata    2.0    2
Gamma   3.0    3

这是你想要的吗?

答案 1 :(得分:0)

一种选择是使用pandas包,您不需要太多的导入。

import pandas as pd

d = {'a':['Alpha','Bata','Gamma'], 'b':['1','2','3'], 'c':['1.0','2.0','3.0']}

df = pd.DataFrame(d)

df将如下所示:

       a  b    c
0  Alpha  1  1.0
1   Bata  2  2.0
2  Gamma  3  3.0

将DataFrame重新写回Excel文件:

df.to_excel("Path to write Excel File + File Name")