Python讀取txt內容寫入xls格式的excel中
阿新 • • 發佈:2019-01-02
由於xlwt目前只支援xls格式,至於xlsx格式,後面會繼續更新
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#記錄有多少行,相當於寫入excel時的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中每一行有多少個數,相當於寫入excel中的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'#需要寫入excel中的Sheet2中,可以自己設定
start_row = 7 #從第7行開始寫
start_col = 3 #從第3列開始寫
inputfile = 'text.txt' #輸入檔案
outputExcel = 'excel_result.xls' #輸出excel檔案
Txt_to_Excel(inputfile,sheetName,start_row,start_col,outputExcel)el)