首页 > 解决方案 > 如何使用python xlsxwriter将列表列表添加到excel中

问题描述

我有一个清单l1=[['a','20,'30],['b','30','40']。我想l1以这种格式插入到 Excel 文件中:

a   20   30
b   30   40 

标签: pythonexcellistxlsxwriter

解决方案


worksheet.write_column()_xlsxwriter

>>> import xlsxwriter
>>> a = [['a','20','30'],['b','30','40']]
>>> cl1 = [i[0] for i in a]                 # ['a', 'b']
>>> cl2 = [','.join(i[1:]) for i in a]      # ['20,30', '30,40']

>>> wbook = xlsxwriter.Workbook('Test.xlsx')
>>> wsheet = wbook.add_worksheet('Test')

>>> wsheet.write_column(0,0, cl1)
>>> wsheet.write_column(0,1, cl2)
>>> wbook.close()

或者

你可以使用熊猫pandas.DataFrame.to_excel

>>> import pandas as pd
>>> df = pd.DataFrame.from_dict({'Column1':cl1,'Column2':cl2})
>>> df
  Column1 Column2
0       a   20,30
1       b   30,40

>>> df.to_excel('a_name.xlsx', header=True, index=False)

推荐阅读