无法写入元组到xslx文件使用python没有Pandas?

z2acfund  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(95)

我试图将输出写入到xslx文件中,但只能写入头,不能写入头下面的数据。

import xlsxwriter

csv_columns = (
    'id', 'name', 'place', 'salary', 'email',
)
details = [{'id':1, 'name': 'A', 'place':'B', 'salary': 2, 'email': 'c@d.com'}, 
          {'id':3, 'name':'C', 'place':'D', 'salary': 4, 'email':'e@f.com'}]

workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet()

for col, name in enumerate(csv_columns):
    worksheet.write(0, col, name)

for row, det in enumerate(details, 1):
    for col, value in enumerate(det):
        worksheet.write(row, col, value)

workbook.close()

此代码仅在xslx文件中写入csv_columns,并在所有行中重复相同操作,如下所示

id  name    place   salary  email
id  name    place   salary  email
id  name    place   salary  email

如何解决xslx中重复列的问题?有帮助吗?
我期待如下:

id    name    place   salary  email
  1    A         B       2       c@d.com
  3    C         D       4       e@f.com
qojgxg4l

qojgxg4l1#

我更正了您的代码。现在它可以正常工作了:

import xlsxwriter

csv_columns = (
    'id', 'name', 'place', 'salary', 'email',
)
values = [(1, 'A', 'B', 2, 'c@d.com'), 
          (3, 'C', 'D', 4, 'e@f.com')]

workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet()

row, col = 0, 0
worksheet.write_row(row, col, csv_columns)
row += 1

for value in values:
    worksheet.write_row(row, col, value)
    row += 1

workbook.close()
kx7yvsdv

kx7yvsdv2#

from openpyxl import Workbook
wb = Workbook()
ws = wb.active

csv_columns = (
    'id', 'name', 'place', 'salary', 'email',
)
details = [{'id':1, 'name': 'A', 'place':'B', 'salary': 2, 'email': 'c@d.com'},
          {'id':3, 'name':'C', 'place':'D', 'salary': 4, 'email':'e@f.com'}]

details_values = [tuple(d.values()) for d in details]
details_values.insert(0, csv_columns)

for row in details_values:
    print(row)
    ws.append(row)

wb.save(output_file_path)

相关问题