【问题标题】:xlsxwriter: create headings from user input and for loopsxlsxwriter:从用户输入和 for 循环创建标题
【发布时间】:2017-09-27 14:37:51
【问题描述】:

我正在尝试创建一个脚本,该脚本接受用户输入并输出一个以用户输入作为列标题的 excel 文件。 因此,如果用户输入:Col1,Col2,Col3 .. 输出应该是一个 excel 文件,每个名称分别包含 3 列:Col1,Col2,Col3。

代码:

import xlsxwriter
from itertools import islice
column_names = input()
template_name = input()

  # add file type to template name
file_type = '.xlsx'
template_name = template_name + file_type

  # create a list of the input names
column_names = column_names.split(",")

  # xlsxwriter column position logic based on user input length
alpha = list(map(chr, range(65, 91)))

z =[]

for letter in  alpha:
    z.append(letter + str(1))

t =[]

for i in islice( z, 0, len(column_names) ):
    t.append(i)

  # Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook(template_name )
worksheet = workbook.add_worksheet()

  # Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

  # Write some data headers.
for name in column_names:
    for i in t:
        worksheet.write(i,name,bold)      

假设我使用以下输入运行脚本:Col1,Col2,Col3,Col4,Col5 脚本的当前输出为: Col5 Col5 Col5 Col5 Col5
Current output

我正在寻找的结果是:Col1 Col2 Col3 Col4 Col5

Expected output

有人知道当前脚本有什么问题吗?为什么创建的 excel 文件有 5 列都命名为 Col5 而不是 Col1 Col2 Col3 Col4 Col5 谢谢!

【问题讨论】:

  • 什么是真正的问题:您有一个列表column_names 包含5 个值:column_names = ['Col1', 'Col2', 'Col3', 'Col4', 'Col5'](您必须检查它)。现在您想以正确的顺序将值写入单元格 A1、B1、C1、D1、E1。不会太难吧?
  • 脚本以正确的顺序将值写入单元格,但它没有写入正确的值。它应该分别将 'Col1'、'Col2'、'Col3'、'Col4'、'Col5' 写入 A1、B1、C1、D1、E1 列。而不是将 Col5 Col5 Col5 Col5 Col5 分别写入 A1、B1、C1 , D1, E1
  • 我就是这么说的。

标签: python for-loop xlsxwriter


【解决方案1】:

在最后尝试 zip:

# Write some data headers.
for i, name in zip(t, column_names):
    worksheet.write(i,name,bold)

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多