博客
关于我
python编程读取写入excel_Python读取txt内容写入xls格式excel中的方法
阅读量:796 次
发布时间:2023-03-07

本文共 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)
return
if __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文件的功能,主要步骤包括:

  • 使用xlwt库创建并准备Excel工作簿和工作表
  • 以读取模式打开文本文件
  • 按行读取文件内容并处理
  • 将每行内容按空格分隔写入Excel中
  • 处理异常情况
  • 保存Excel文件
  • 代码注释清晰,易于理解,主要参数说明如下:

    • inputTxt:输入文本文件路径
    • sheetName:目标Excel工作表名称
    • start_row:写入的起始行数
    • start_col:写入的起始列数
    • outputExcel:输出Excel文件路径

    代码运行时,可以直接调用函数或通过主程序调用。

    转载地址:http://jnofk.baihongyu.com/

    你可能感兴趣的文章