将列表值写入Excel

2024-09-27 00:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下值的列表:

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()

Tags: thefrom脚本onorderthemelistwrite
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()

您可以尝试:

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')

相关问题 更多 >

    热门问题