当前位置:   article > 正文

python,把txt转为xls,xlsx,使用xlwt, xlsxriter openpyxl三种包_item = line.split('\t')[i]

item = line.split('\t')[i]

第一种:xlwt

  1. import xlwt
  2. f = open(file_new,encoding="gbk")
  3. xls = xlwt.Workbook()
  4. #生成excel的方法,声明excel
  5. sheet = xls.add_sheet('sheet1', cell_overwrite_ok=True)
  6. x = 0
  7. while True:
  8. # 按行循环,读取文本文件
  9. line = f.readline()
  10. if not line:
  11. break # 如果没有内容,则退出循环
  12. for i in range(len(line.split('\t'))):
  13. item = line.split('\t')[i]
  14. sheet.write(x, i, item) # x单元格经度,i 单元格纬度
  15. x += 1 # excel另起一行
  16. f.close()

第二种:openpyxl

  1. import openpyxl
  2. from openpyxl.utils import get_column_letter
  3. f = open(file_new,encoding="gbk")
  4. wb = openpyxl.Workbook()
  5. ws = wb.active
  6. ws = wb.create_sheet()
  7. ws.title = 'Sheet1'
  8. row = 0
  9. for line in f:
  10. row +=1
  11. line = line.strip()
  12. line = line.split('\t')
  13. col = 0
  14. for j in range(len(line)):
  15. col += 1
  16. ws.cell(column= col,row = row,value=line[j].format(get_column_letter(col)))
  17. wb.save("保存的文件名" )

第三种:xlsxwriter

  1. import xlsxwriter
  2. wo = xlsxwriter.Workbook("文件名.xlsx")
  3. sheet = wo.add_worksheet()
  4. x = 0
  5. while True:
  6. # 按行循环,读取文本文件
  7. line = f.readline()
  8. if not line:
  9. break # 如果没有内容,则退出循环
  10. for i in range(len(line.split('\t'))):
  11. item = line.split('\t')[i]
  12. sheet.write(x, i, item) # x单元格经度,i 单元格纬度
  13. x += 1 # excel另起一行
  14. wo.close()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/44864
推荐阅读
相关标签
  

闽ICP备14008679号