Excel工作表将所有数据写入一列

我有一个问题写我的文本到Excel表:

这是我的代码:

import xlwt wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter col = 0 f = open('newfile.txt') for line in f: L = line.split('\t') for c in L: sheet.write(row,col,c) row += 1 wbk.save('example12.xls') 

这里是input.txt

 Ename DCname Competency Effort Eng01 DC1 SW 30 Eng02 DC2 HW 30 Eng03 DC3 ME 40 Eng04 DC2 SW 20 Eng05 DC3 FW 40 Eng06 DC3 SW 35 Eng07 DC1 HW 25 Eng08 DC3 SW 30 Eng09 DC1 HW 35 Eng10 DC3 SW 20 Eng11 DC1 HW 40 Eng12 DC3 SW 40 Eng13 DC1 HW 30 Eng14 DC1 HW 30 Eng15 DC3 FW 40 

但input.txt只写入一列,我怎么能把它写入不同的列?

你的问题在这里:

 for line in f: L = line.split('\t') for c in L: sheet.write(row,col,c) row += 1 

col永远不会从0改变,所以它总是写入同一列。 在循环过程中可能会增加它,但最好使用enumerateenumerate返回循环的每个迭代的索引,因此您可以计算您正在使用的数字列。 喜欢这个:

 for line in f: L = line.split('\t') for i,c in enumerate(L): sheet.write(row,i,c) row += 1 

i是在行中find的列的编号,所以它会将每一条数据写入下一列。

假设您的input文本文件是用制表符分隔的,以下应该工作:

 import csv with open("input.txt", "r") as f_input, open("output.csv", "wb") as f_output: csv_input = csv.reader(f_input, delimiter="\t") csv_output = csv.writer(f_output) text = list(csv_input) csv_output.writerows(text) 

这会给你一个可以在Excel中打开的文件,如下所示:

 Ename,DCname,Competency,Effort Eng01,DC1,SW,30 Eng02,DC2,HW,30 Eng03,DC3,ME,40 Eng04,DC2,SW,20 Eng05,DC3,FW,40 Eng06,DC3,SW,35 Eng07,DC1,HW,25 Eng08,DC3,SW,30 Eng09,DC1,HW,35 Eng10,DC3,SW,20 Eng11,DC1,HW,40 Eng12,DC3,SW,40 Eng13,DC1,HW,30 Eng14,DC1,HW,30 Eng15,DC3,FW,40 

如果要直接使用openpyxl创buildXLSX文件,可以使用以下内容:

 import csv from openpyxl.workbook import Workbook with open("input.txt", "r") as f_input: csv_input = csv.reader(f_input, delimiter="\t") wb = Workbook() ws1 = wb.active ws1.title = "Locations" for row in csv_input: ws1.append(row) wb.save(filename="output.xlsx") 
Interesting Posts