2016-08-12 66 views
2

我想使用XlsxWriter将数据写入Excel列。为每次迭代编写一组“数据”。每套应该写在一个单独的列。我该怎么做呢?
我试图玩弄的col值如下:是否有可能为XlsxWriter中的每个迭代创建一个新列

  • [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() 

回答

0

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

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

您应该将循环外部的xlsx文件创建。可能是你的open()这个文本文件在同一个地方。

+0

嗯,不知道解决迭代通过列虽然? –

+0

查看上面的更新。 – jmcnamara

相关问题