Python 3.3 - 将字典粘贴到Excel

时间:2014-12-28 15:30:34

标签: python dictionary paste xlwt

我想粘贴以下词典:

{'Olive Oil': 221.0, 'Ham - Pork': 216.14999999999998, 'Feta Cheese': 163.125, 'Vinegar': 5.1, 'Cherry Tomatoes': 22.5, 'Cucumber': 22.5}

在新的Excel工作簿中:

newbook = xlwt.Workbook(encoding="utf-8")
sheet = newbook.add_sheet('Table')

使用xlwt

2 个答案:

答案 0 :(得分:1)

我使用了类似的东西。希望这有帮助

import xlsxwriter

excelBook = xlsxwriter.Workbook('data.xlsx')
excelSheet = excelBook.add_worksheet()

elements = {'a':['e1','e2','e3'],
            'b':['e1','e2']
           } 
row = 0
col = 0

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

excelBook.close()

你也可以使用DictWriter(在csv中)。

答案 1 :(得分:0)

这是我的解决方案,如果我可以使用我自己的library,它间接使用xlwt-future:

>>> import pyexcel as pe
>>> import pyexcel.ext.xls
>>> data={'Olive Oil': 221.0, 'Ham - Pork': 216.14999999999998, 'Feta Cheese': 163.125, 'Vinegar': 5.1, 'Cherry Tomatoes': 22.5, 'Cucumber': 22.5}
>>> data
{'Olive Oil': 221.0, 'Ham - Pork': 216.14999999999998, 'Vinegar': 5.1, 'Cherry Tomatoes': 22.5, 'Feta Cheese': 163.125, 'Cucumber': 22.5}
>>> v=[data.keys(), data.values()]
>>> v
[['Olive Oil', 'Ham - Pork', 'Vinegar', 'Cherry Tomatoes', 'Feta Cheese', 'Cucumber'], [221.0, 216.14999999999998, 5.1, 22.5, 163.125, 22.5]]
>>> sheet=pe.Sheet(v)
>>> sheet
Sheet Name: pyexcel
+-----------+------------+---------+-----------------+-------------+----------+
| Olive Oil | Ham - Pork | Vinegar | Cherry Tomatoes | Feta Cheese | Cucumber |
+-----------+------------+---------+-----------------+-------------+----------+
| 221       | 216.150    | 5.100   | 22.500          | 163.125     | 22.500   |
+-----------+------------+---------+-----------------+-------------+----------+
>>> sheet.transpose()
>>> sheet
Sheet Name: pyexcel
+-----------------+---------+
| Olive Oil       | 221     |
+-----------------+---------+
| Ham - Pork      | 216.150 |
+-----------------+---------+
| Vinegar         | 5.100   |
+-----------------+---------+
| Cherry Tomatoes | 22.500  |
+-----------------+---------+
| Feta Cheese     | 163.125 |
+-----------------+---------+
| Cucumber        | 22.500  |
+-----------------+---------+
>>> sheet.save_as("myfile.xls")