1

I'm having a problem writing my text to an excel sheet:

Here's my code:

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')

And here's 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  

But input.txt is writing into only one column, how can I get it to write into different columns?

4

2 回答 2

1

你的问题在这里:

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

col永远不会改变,0所以它总是写入同一列。您可以在该循环期间增加它,但最好使用enumerate. enumerate返回循环每次迭代的索引,因此您可以计算您使用它的数字列。像这样:

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

i是在该行中找到的列的编号,因此它将每条数据写入下一列。

于 2015-08-11T10:52:10.853 回答
0

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

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创建XLSX文件,可以使用以下:

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") 
于 2015-08-11T10:32:10.467 回答