【问题标题】:How to choose an alternative name for sheet in xls file from python?如何从 python 为 xls 文件中的工作表选择替代名称?
【发布时间】:2016-05-31 11:05:02
【问题描述】:

我想将我的数据从 python 传输到各种工作表中的 excel 文件。所以我需要更改工作表的名称以选择合适的工作表来书写。我已经编写了此代码,但它不接受我在ws = wb.add_sheet("Patch Size %s",%(wo)) 行中为我的工作表提供替代名称。

patch = [3, 5, 7, 9, 11, 13, 15, 17, 19, 25, 37, 49, 55, 60, 70, 80]

DATA = (("x", 1,),
        ("x",1),
        ("x",1),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x", 1),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x",1 ),
        ("x", 1),
        ("x",1),)

whch = 25
wb = xlwt.Workbook()
w0 = 0 
while whch != patch[w0]:
    w0 = w0+1
ws = wb.add_sheet("Patch Size %s",%(wo))
for i, row in enumerate(DATA):
    for j ,col in enumerate(row):
        if j == 0:
            ws.write(i, j, col)
        elif j == 1:
            ws.write(i, which+j, col)
ws.col(0).width = 456 * max([len(row[0]) for row in DATA])

你知道我该怎么做吗?

谢谢。

【问题讨论】:

    标签: python xls


    【解决方案1】:

    您的代码中有很多错误。试试这个:

    whch = 25
    wb = xlwt.Workbook()
    w0 = 0 
    while whch != patch[w0]:
        w0 = w0+1
    ws = wb.add_sheet("Patch Size %s" %(w0)) # no comma needed, changed wo to w0
    for i, row in enumerate(DATA):
        for j ,col in enumerate(row):
            if j == 0:
                ws.write(i, j, col)
            elif j == 1:
                ws.write(i, whch+j, col)  # replaced which with whch
    ws.col(0).width = 456 * max([len(row[0]) for row in DATA])
    

    假设它们是拼写错误,我通过进行看似最合理的替换(例如which --> whch)来修复错误,但您可能需要仔细检查上述内容是否仍然符合您的预期去做。

    【讨论】:

      【解决方案2】:

      您的错误似乎在于您的工作表名称字符串格式(您的逗号放错了位置),而不是来自 xlwt :

      ws = wb.add_sheet("Patch Size %s",%(wo))
      

      应该是

      ws = wb.add_sheet("Patch Size %s"%(wo))
      

      ws = wb.add_sheet("Patch Size {0}".format(wo))
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2016-02-28
        • 2019-06-28
        • 2020-02-08
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-06
        相关资源
        最近更新 更多