简体   繁体   English

使用 pandas xlsxwriter 写入 excel 表中的多行

[英]Write to multiple rows in excel sheet using pandas xlsxwriter

I am trying to write values to excel sheet using xlsxwriter.我正在尝试使用 xlsxwriter 将值写入 excel 表。

When trying to write the data to the second row, the data is overwriting to the first row itself.当试图将数据写入第二行时,数据会覆盖到第一行本身。 Since i am new to xlsx writer i am unable to figure out where to iterate over.由于我是 xlsx 作家的新手,我无法弄清楚在哪里迭代。

import pandas as pd
from pandas import ExcelWriter


def outputInExcel(valueToExcel):
    with ExcelWriter('pandas.xlsx', mode='A', engine='xlsxwriter') as writer:
        # write operation perform
        valueToExcel.to_excel(writer,startrow=1, header=False)
        worksheet = writer.sheets['Sheet1']
        workbook = writer.book
        header_format = workbook.add_format({
            'bold': True,
            'text_wrap': True,
            'valign': 'top',
            'fg_color': '#D7E4BB',
            'border': 1})

        for row_num,col_num,value in enumerate(valueToExcel.columns.values):
            worksheet.write(0, col_num + 1, value, header_format)
        writer.save()


file = "Search.xlsx"#image  reference
df = pd.read_excel(file)
for index, row in df.iterrows():
    valueToExcel = pd.DataFrame({
        'Manager': [row['Manager']], 'Policy Name': [row['Policy Name']], 'Numbers': [row['Numbers'], 'Source IP': [row['Source']], 'Destination IP': [row['Destination']]
    })
    outputInExcel(valueToExcel)

I am expecting a output like this.我期待像这样的 output。

在此处输入图像描述

I am getting a output like this.我得到一个像这样的 output。

在此处输入图像描述

There are some problems with your code;您的代码存在一些问题; you override the same row every time and you restart the writer every row, so that is not very efficient.您每次都覆盖同一行,并且每行都重新启动编写器,因此效率不高。 My recommendation is to write the entire dataframe in one go:我的建议是将整个 dataframe 写在一个 go 中:

writer = ExcelWriter('pandas.xlsx', mode='A', engine='xlsxwriter')
worksheet = writer.sheets['Sheet1']
workbook = writer.book
header_format = workbook.add_format({
  'bold': True,
  'text_wrap': True,
  'valign': 'top',
  'fg_color': '#D7E4BB',
  'border': 1
})
# write the header separately so you can format it
for col_num, value in enumerate(['Manager', 'Policy Name', 'Numbers', 'Source IP', 'Destination IP']):
  worksheet.write(0, col_num + 1, value, header_format)

df = pd.read_excel(file)
# if you only want specific columns
df = df[['Manager', 'Policy Name', 'Numbers', 'Source', 'Destination']]
df.to_excel(writer, sheet_name=name, index=False, header=False, startrow=1)
writer.save()

I tried to keep it as much equal to your code as possible, I just removed the loop and moved the code out of the function我试图让它尽可能与您的代码相同,我只是删除了循环并将代码移出 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM