博客
关于我
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/

    你可能感兴趣的文章
    python redis连接,在Python中使用Redis连接池的正确方法
    查看>>
    python regex_Python RegEx
    查看>>
    python requests post 中文结果请求得到unicode
    查看>>
    Python Requests接口自动化测试实战
    查看>>
    Python requests模块
    查看>>
    python request与grequests该如何选择
    查看>>
    python request模块
    查看>>
    Python requirements.txt的使用方法
    查看>>
    Python REST(Web 服务)框架的推荐?
    查看>>
    Python rsa 加密
    查看>>
    Python RSA操作
    查看>>
    Python轻松实现统计学中重要的相关性分析
    查看>>
    Python scrapy 常见问题及解决 【遇到的坑】
    查看>>
    Python Seborn热图数据的动态更新
    查看>>
    Python Seborn绘制空白直方图
    查看>>
    Python Selenium - 获取href值
    查看>>
    Python Selenium实现自动化测试及Chrome驱动使用!
    查看>>
    Python Selenium搭建UI自动化测试框架
    查看>>
    Python Selenium模块详解
    查看>>
    Python selenium爬取影评生成词云图
    查看>>