2017-09-01 94 views
0

我想用从文本文件读取的数据填充Excel工作表。 我的脚本打开一个文本文件,然后将某些属性放入列表中。然后我想填充我的Excel表格中的数据。从Python列表中填充Excel

我在同一位置有很多txt文档,所以我的脚本通过文件循环。

我的代码有什么问题?它只填充一行。

import xlwt 
import os 


output = 'D:\Holding_Area\\test.xls' 
file_path='Y:\\Testing\\Crashes' 
pathappend=[] 
r=1 

for a in os.listdir(file_path): 
    pathappend.append(file_path+'\\'+a) 


def main(): 
    for x in pathappend: 
     appendlist=[] 
     wbk = xlwt.Workbook() 
     sheet = wbk.add_sheet('python', cell_overwrite_ok=True)  
     file = open(x) 
     lines = file.readlines() 
     appendlist.append(lines[1][2:10]) 
     appendlist.append(lines[1][13:21]) 
     appendlist.append(lines[4][15:30]) 
     appendlist.append(lines[10][13:22]) 
     appendlist.append(lines[11][9:28]) 
     appendlist.append(lines[22]) 
     appendlist.append(lines[31][84:113]) 
     appendlist.append(lines[27:29]) 
     file.close() 
     for i,e in enumerate(appendlist): 
      sheet.write(r,i,e) 
      r+1 


     wbk.save(output) 
main() 
+0

它似乎是一个问题,它覆盖自己 – tommy45

回答

0

问题与'r + 1'应该是'r + = 1';如下所示:

import xlwt 
import os 


output = 'D:\Holding_Area\\test.xls' 
file_path='Y:\\Testing\\Crashes' 
pathappend=[] 
r=1 

for a in os.listdir(file_path): 
    pathappend.append(file_path+'\\'+a) 


def main(): 
    for x in pathappend: 
     appendlist=[] 
     wbk = xlwt.Workbook() 
     sheet = wbk.add_sheet('python', cell_overwrite_ok=True)  
     file = open(x) 
     lines = file.readlines() 
     appendlist.append(lines[1][2:10]) 
     appendlist.append(lines[1][13:21]) 
     appendlist.append(lines[4][15:30]) 
     appendlist.append(lines[10][13:22]) 
     appendlist.append(lines[11][9:28]) 
     appendlist.append(lines[22]) 
     appendlist.append(lines[31][84:113]) 
     appendlist.append(lines[27:29]) 
     file.close() 
     for i,e in enumerate(appendlist): 
      sheet.write(r,i,e) 
      r+=1 


    wbk.save(output) 
main()