【问题标题】:Excel sheet writing all data in one columnExcel工作表在一列中写入所有数据
【发布时间】:2015-08-11 10:19:43
【问题描述】:

我在将文本写入 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 只写入一列,我怎样才能让它写入不同的列?

【问题讨论】:

    标签: python excel xlwt writing xlw


    【解决方案1】:

    你的问题在这里:

    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 是在该行中找到的列号,因此它将每条数据写入下一列。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这个现在已经不重要了,OP里面有更多的信息。
      • 如何使用 csv 和 xlwt 从 excel 请求输入
      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多