如何使用openpyxl将列表内容写入Excel工作表

时间:2018-12-23 06:21:17

标签: python-3.x openpyxl

我有以下列表:

d_list = ["No., Start Name, Destination, Distance (miles)",
"1,ALBANY,NY CRAFT,28",
"2,GRACO,PIONEER,39",
"3,FONDA,ROME,41",
"4,NICCE,MARRINERS,132",
"5,TOUCAN,SUBVERSIVE,100",
"6,POLL,CONVERGENCE,28",
"7,STONE HOUSE,HUDSON VALLEY,9",
"8,GLOUCESTER GRAIN,BLACK MUDD POND,75",
"9,ARMY LEAGUE,MUMURA,190",
"10,MURRAY,FARMINGDALE,123"]

因此,基本上,该列表由数千个元素组成(这里仅显示了10个示例),每个元素都是由逗号分隔的字符串。我想将此写入工作簿中的新工作表中。

注意:该工作簿已经存在并且包含其他工作表,我只是添加了一个包含此数据的新工作表。

我的代码:

    import openpyxl
    wb = openpyxl.load_workbook('data.xlsx')
    sheet = wb.create_sheet(title='distance')
    for i in range(len(d_list)):
        sheet.append(list(d_list[i]))

在此示例中,我期望有11行数据,每行4列。但是,我得到了11行,但是每个单元格中写入了每个字符串的每个字符!我想快到了...我想念什么? (注意:我已经阅读了与该主题相关的所有可用帖子,但是找不到能回答这种特定类型问题的任何帖子,因此我在询问)。

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以使用pandas解决此问题:

1。)将列表转换为数据框:

In [231]: l
Out[231]: 
['No., Start Name, Destination, Distance (miles)',
 '1,ALBANY,NY CRAFT,28',
 '2,GRACO,PIONEER,39',
 '3,FONDA,ROME,41',
 '4,NICCE,MARRINERS,132',
 '5,TOUCAN,SUBVERSIVE,100',
 '6,POLL,CONVERGENCE,28',
 '7,STONE HOUSE,HUDSON VALLEY,9',
 '8,GLOUCESTER GRAIN,BLACK MUDD POND,75',
 '9,ARMY LEAGUE,MUMURA,190',
 '10,MURRAY,FARMINGDALE,123']

In [228]: df = pd.DataFrame([i.split(",") for i in l])

In [229]: df
Out[229]: 
      0                 1                2                  3
0   No.        Start Name      Destination   Distance (miles)
1     1            ALBANY         NY CRAFT                 28
2     2             GRACO          PIONEER                 39
3     3             FONDA             ROME                 41
4     4             NICCE        MARRINERS                132
5     5            TOUCAN       SUBVERSIVE                100
6     6              POLL      CONVERGENCE                 28
7     7       STONE HOUSE    HUDSON VALLEY                  9
8     8  GLOUCESTER GRAIN  BLACK MUDD POND                 75
9     9       ARMY LEAGUE           MUMURA                190
10   10            MURRAY      FARMINGDALE                123

2。)在新的工作表的4列中将上述数据框写入excel:

import numpy as np
from openpyxl import load_workbook

path = "data.xlsx"

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book

df.to_excel(writer, sheet_name = 'distance')
writer.save()
writer.close()