本文共 1324 字,大约阅读时间需要 4 分钟。
def Txt_to_Excel(inputTxt, sheetName, start_row, start_col, outputExcel): with codecs.open(inputTxt, 'r') as fr: wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(sheetName) line_number = 0 row_excel = start_row try: for line in fr: line_number += 1 row_excel += 1 line = line.strip() if not line: continue cols = line.split(' ') len_line = len(cols) col_excel = start_col for j in range(len_line): ws.write(row_excel, col_excel, cols[j]) col_excel += 1 if len_line == 0: break except: pass wb.save(outputExcel) returnif __name__ == '__main__': sheetName = 'Sheet2' start_row = 7 start_col = 3 inputfile = 'text.txt' outputExcel = 'excel_result.xls' Txt_to_Excel(inputfile, sheetName, start_row, start_col, outputExcel) 以上代码实现了将文本文件内容写入Excel文件的功能,主要步骤包括:
代码注释清晰,易于理解,主要参数说明如下:
代码运行时,可以直接调用函数或通过主程序调用。
转载地址:http://jnofk.baihongyu.com/