[英]How to add a list of list into excel using python xlsxwriter
I have a list l1=[['a','20,'30],['b','30','40']
.我有一个列表
l1=[['a','20,'30],['b','30','40']
。 I want l1
to be inserted in an Excel file with this format:我希望将
l1
插入到具有以下格式的 Excel 文件中:
a 20 30
b 30 40
Using worksheet.write_column()
with xlsxwriter
将
worksheet.write_column()
与xlsxwriter
一起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()
Or或者
You can use pandas pandas.DataFrame.to_excel
您可以使用熊猫
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)
Try this:尝试这个:
import openpyxl
l1 = [['a','20','30'],['b','30','40']]
wb = openpyxl.Workbook()
sheet = wb.active
le_ = len(l1)
for i in l1:
c1 = sheet.cell(row=1,column=1)
c1.value = i[0]
c2 = sheet.cell(row=1,column=2)
c2.value = ' '.join(each for each in i[1:])
wb.save("demo1.xlsx")
In sheet.cell(row=1,column=1)
you can point to specific cell using row number and column number and can store data in what ever format you want在
sheet.cell(row=1,column=1)
您可以使用行号和列号指向特定单元格,并且可以以您想要的任何格式存储数据
You can try:你可以试试:
import pandas as pd
l1 = [['a','20', '30'], ['b','30', '40']]
df = pd.DataFrame({'col1': [l[0] for l in l1],
'col2': [l[1:3] for l in l1]})
df.to_excel('output.xlsx')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.