Python reads txt content and writes to methods in xls format excel

  • 2020-12-09 00:56:54
  • OfStack

As xlwt currently only supports xls format, the xlsx format will be updated later


import xlwt
import codecs

def Txt_to_Excel(inputTxt,sheetName,start_row,start_col,outputExcel):
 fr = codecs.open(inputTxt,'r')
 wb = xlwt.Workbook(encoding = 'utf-8')
 ws = wb.add_sheet(sheetName)

 line_number = 0# Records how many rows are equivalent to writing excel At the time of the i . 
 row_excel = start_row
 try:
  for line in fr :
   line_number +=1
   row_excel +=1
   line = line.strip()
   line = line.split(' ')
   len_line = len(line)#list Each of the 1 How many rows are there? That's the same as writing excel In the j
   col_excel = start_col
   for j in range(len_line):
    print (line[j])
    ws.write(row_excel,col_excel,line[j])
    col_excel +=1
    wb.save(outputExcel)
 except:
  print ('')


if __name__=='__main__':
 sheetName = 'Sheet2'# Need to write excel In the Sheet2 , you can set it yourself 
 start_row = 7 # From the first 7 Line began to write 
 start_col = 3 # From the first 3 Column to write 
 inputfile = 'text.txt' # The input file 
 outputExcel = 'excel_result.xls' # The output excel file 
 Txt_to_Excel(inputfile,sheetName,start_row,start_col,outputExcel)el)

Related articles: