2017-07-19 54 views
1

我想在python中讀取一個字典並將其放入一個excel工作表,其中的按鍵顯示在工作表的標題部分並且值位於列中。我很接近,我只是想念一些小的東西,不能弄清楚這裏是我的代碼。注意我用的方法很多進口如何在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() 

回答

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 

要寫入數據幀回到Excel文件:

df.to_excel("Path to write Excel File + File Name") 
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() 

這將數據置於此地rmat:

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

這是你想要的嗎?

+0

確切地感謝您花時間回答我的問題。祝你有美好的一天。 –