将列表值写入Excel

问题描述 投票:0回答:2

我有一个值如下的列表:

print(list_Theme)
print(list_SubTheme)
print(list_Quote)

['Operating environment', 'Competitive advantage']
['Regional Demand', None]
["In China Cash flow from operating activities was $670 million, up 19%.ABB's regional and country order trends for the third quarter are illustrated on Slide 4.", 'Specifically, in the United States, our largest market, Electrification order growth was robust apart from large orders, whichhad a tough comparison base.']

我希望输出如下所示的excel:enter image description here

我已经编写了以下脚本,但是有人可以指出如何实现相同的脚本吗?

 import xlsxwriter
 outWorkbook=xlsxwriter.Workbook("out.xlsx")
 outSheet=outWorkbook.add_worksheet()
 outSheet.write("A1","Theme")
 outSheet.write("B1","Sub-Theme")
 outSheet.write("C1","Quote")
 #row=0
 #col=0
 #I am stuck here on how to proceed? Should I use write_row? or Is there a better way?


 outWorkbook.close()
python xlsxwriter
2个回答
1
投票

您可以尝试:

import pandas as pd
import numpy as np

#Create a DataFrame
lists = {
    'list_Theme':['Operating environment', 'Competitive advantage'],
    'list_SubTheme':['Regional Demand', None],

       'list_Quote':["In China Cash flow from operating activities was $670 million, up 19%.ABB's regional and country order trends for the third quarter are illustrated on Slide 4.", 'Specifically, in the United States, our largest market, Electrification order growth was robust apart from large orders, whichhad a tough comparison base.']}

df = pd.DataFrame(lists,columns=['list_Theme','list_SubTheme','list_Quote'])

df.to_excel(r'Path where you want to store the exported excel file\File Name.xlsx')

2
投票

有很多写入Excel文件的方法,但是当您使用xlsxwriter时;让我为您使用相同的方法。

您可以尝试以下代码:

import xlsxwriter

letters = ['A', 'B', 'C']

data = [{'Theme':'Operating environment','Sub-Theme': 'Regional Demand','Quote':'In China Cash flow from operating activities was $670 million, up 19%.ABB\'s regional and country order trends for the third quarter are illustrated on Slide 4.'},{'Theme':'Competitive advantage','Sub-Theme': 'None','Quote':'Specifically, in the United States, our largest market, Electrification order growth was robust apart from large orders, which had a tough comparison base.'}]

FileName="Output.xlsx"
workbook = xlsxwriter.Workbook(FileName)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

header_col_name=['Theme','Sub-Theme','Quote']
for i in header_col_name:
      worksheet.write(''+letters[header_col_name.index(i)]+'1', i, bold)
i=2
for d in data:
     for j in header_col_name:
          worksheet.write(''+letters[header_col_name.index(j)]+ str(i), d[j])
     i=i+1
workbook.close()
© www.soinside.com 2019 - 2024. All rights reserved.