excel - 是否可以在 XlsxWriter 中为每次迭代创建一个新列

标签 excel python-3.x xlsxwriter

我想使用 XlsxWriter 将数据写入 Excel 列。每次迭代都会写入一组“数据”。每组应写在单独的列中。我该怎么做呢?
我试过玩col值如下:

  • [1]我定义i=0在循环之外,然后将其增加 1并设置col=i .完成后输出为空白。对我来说,这是最合乎逻辑的解决方案,我不知道为什么它不起作用。
  • [2] i在循环内部定义。当发生这种情况时,会写入一列。
  • [3]我定义col标准方式。这按预期工作:写入一列。

  • 我的代码:
    import xlsxwriter
    
    txt_file = open('folder/txt_file','r')
    lines = dofile.readlines()
    
    # [1]Define i outside the loop. When this is used output is blank.
    i = 0
    for line in lines:
    
        if condition_a is met:
            #parse text file to find a string. reg_name = string_1.
    
        elif condition_b:
            #parse text file for a second string. esto_name = string_2.
    
        elif condition_c:
            #parse text file for a group of strings. 
            # use .split() to append these strings to a list.
            # reg_vars = list of strings.
    
            #[2] Define i inside the loop. When this is used one column gets written. Relevant for [1] & [2].
            i+=1 #Increment for each loop
            row=1
            col=i #Increments by one for each iteration, changing the column.
    
    
            #[3] #Define col =1. When this is used one column also gets written.
            col=1 
    
            #Open Excel
            book= xlsxwriter.Workbook('folder/variable_list.xlsx')
            sheet = book.add_worksheet()
    
            #Write reg_name
            sheet.write(row, col, reg_name)
            row+=1
    
             #Write esto_name
            sheet.write(row, col, esto_name)
            row+=1
            #Write variables
            for variable in reg_vars:
                row+=1
                sheet.write(row, col, variable)   
    
        book.close()
    

    最佳答案

    您可以使用 XlsxWriter write_column()方法将数据列表写入列。

    但是,在这种特殊情况下,问题似乎是您正在通过 xlsxwriter.Workbook() 创建一个新的重复文件。每次通过condition_c循环的一部分。因此 col 的最后一个值被使用,并且整个文件在下一次循环中被覆盖。

    您可能应该将 xlsx 文件的创建移到循环之外。可能和你在同一个地方open()文本文件。

    关于excel - 是否可以在 XlsxWriter 中为每次迭代创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919007/

    相关文章:

    mysql - 如何使用 Apache Drill 同时处理 Excel 文档和 RDBMS 中的源?

    excel - 在 Excel 中搜索并返回多个文本字符串

    python - 用随机数填充 Excel 单元格

    python - 使用 XlsxWriter 将单元格中的文本定向为垂直?

    excel - Excel 是否有 SUMPRODUCT IF 内置函数?

    excel - Visual Basic for Applications(VBA)编译错误: Procedure declaration does not match description of event or procedure having the same name

    python-3.x - 应用Python lambda : if condition giving syntax error

    python-3.x - 如何修复 wxPython 模块中 wxPyDeprecationWarning 的警告?

    python-3.x - ZeroDivisionError : float division by zero (python 3. 6)

    excel - xlsxwriter 将括号添加到公式中