gpt4 book ai didi

python 如何从 xlsxwriter 移植到 xlwt

转载 作者:行者123 更新时间:2023-11-30 23:15:08 28 4
gpt4 key购买 nike

我想在 xlwt 中重新创建 xlsxwriter 程序。我在写一行时遇到问题。有人可以帮助我使用 xlwt 模块吗?我发现很多 xlwt 使用 enumerate 的代码,但我对 xlwt 不太熟悉。我遇到的问题是,xlwt 将整个列表作为字符串写入第一个单元格中,因此我最终得到一列充满数据的结果。 xlsxwriter 将列表中的每个项目写入其单独的单元格中,这就是我想要使用 xlwt 执行的操作。如果有人能引导我走向正确的方向,我将不胜感激。谢谢

这是我的代码:

def xlsxwriter_res(result):
workbook = xlsxwriter.Workbook('filename.xlsx')

for key,value in result.items():
worksheet = workbook.add_worksheet(key)
row, col = 0, 0

for line in value:
worksheet.write_row(row, col, line) ### Writes each item in list in separate cell
row += 1

workbook.close()


def xlwt_res(result):
workbook = xlwt.Workbook(encoding="utf-8")

for key,value in result.items():
worksheet = workbook.add_sheet(key)
row, col = 0, 0

for line in value:
worksheet.write(row, col, line) ### Writes the whole list as string in one cell
row += 1

workbook.save('filename.xls')

最佳答案

尝试一下:

import xlwt


def xlwt_res(result):
workbook = xlwt.Workbook(encoding="utf-8")

for key, value in result.items():
worksheet = workbook.add_sheet(key)
row = 0 # we assign 'col' later instead

for line in value:
# we're going to iterate over the line object
# and write directly to a cell, incrementing the column id
for col, cell in enumerate(line):
worksheet.write(row, col, cell) # writes the list contents just like xlsxwriter.write_row!
row += 1

workbook.save('filename.xls')


xlwt_res({'one': ["just one element"], 'two': ["that's a list", "did you know it"], 'three': ["let's", "have", "3"]})

因此,xlwtxlsxwriter 都会产生相同的结果:
enter image description here

关于python 如何从 xlsxwriter 移植到 xlwt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com