python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python3 Excel转TXT

Python3脚本实现Excel与TXT的智能转换

作者:XMYX-0

在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式,本文将使用Python3实现Excel与TXT的智能转换,需要的可以了解下

在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式。本文将手把手教你如何用Python轻松实现Excel到TXT的智能转换,让重复性工作自动化,效率提升立竿见影!

场景应用:为什么需要这种转换

当遇到以下场景时,这个脚本将成为你的得力助手:

技术解析:代码实现详解

核心代码展示

import openpyxl
import os

def xlsx_to_txt(file_path, output_dir="output", header_row=1):
    """
    将Excel文件内容转换为多个TXT文件
    
    参数:
    file_path (str): Excel文件路径
    output_dir (str): 输出目录,默认为"output"
    header_row (int): 标题行数,默认为1
    """
    try:
        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)
        
        # 加载Excel工作簿
        workbook = openpyxl.load_workbook(file_path)
        sheet = workbook.active

        # 遍历每一行
        for row_num, row in enumerate(sheet.iter_rows(values_only=True), start=1):
            if row_num > header_row:  # 跳过标题行
                # 检查序号列是否为空
                if row[0] is None:
                    print(f"警告:第{row_num}行缺少序号,已跳过")
                    continue
                    
                # 检查内容列是否为空
                if row[1] is None:
                    print(f"警告:第{row_num}行内容为空,已跳过")
                    continue
                    
                # 清理文件名中的非法字符
                safe_filename = "".join(c for c in str(row[0]) if c.isalnum() or c in (' ', '_')).rstrip()
                if not safe_filename:
                    print(f"警告:第{row_num}行文件名无效,已跳过")
                    continue
                    
                # 写入文件
                output_path = os.path.join(output_dir, f"{safe_filename}.txt")
                try:
                    with open(output_path, "w", encoding="utf-8") as txt_file:
                        txt_file.write(str(row[1]))
                    print(f"成功创建文件: {output_path}")
                except Exception as e:
                    print(f"错误:无法写入文件 {output_path} - {str(e)}")
                        
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 不存在!")
    except Exception as e:
        print(f"程序运行出错: {str(e)}")

# 示例调用
xlsx_to_txt('data.xlsx')

改进点说明

1.输出目录管理

新增output_dir参数,自动创建输出目录

2.文件名安全处理

过滤文件名中的非法字符,避免创建文件失败

3.空值双重检查

同时检查文件名和内容列,确保数据完整性

4.错误处理增强

添加全面的异常捕获,提高程序健壮性

5.进度反馈

添加成功/失败提示,方便追踪处理结果

实战演练:从Excel到TXT的完整流程

准备数据示例(data.xlsx)

执行转换

data.xlsx与test.py再同一级目录

python3 test.py

生成结果

成功创建文件: output/10.txt
警告:第3行缺少序号,已跳过
成功创建文件: output/12.txt
警告:第5行内容为空,已跳过
成功创建文件: output/14.txt
警告:第7行缺少序号,已跳过
成功创建文件: output/16.txt
成功创建文件: output/17.txt
成功创建文件: output/18.txt

功能扩展:按需定制你的转换器

1.多列内容合并

content = '\n'.join([str(cell) for cell in row[1:] if cell])

2.自动编号

filename = f"{row_num}_{safe_filename}"

3.保留原始格式

from openpyxl.styles import numbers
if cell.number_format == numbers.FORMAT_DATE_XLSX22:
    # 处理日期格式

4.添加日志系统

import logging
logging.basicConfig(filename='converter.log', level=logging.INFO)

最佳实践与避坑指南

1.数据预处理

2.性能优化

3.异常处理

4.版本兼容

应用场景升级:企业级解决方案

对于更复杂的业务需求,可以扩展为:

1.云端部署方案

2.邮件自动发送

import smtplib
# 将生成的txt文件作为附件自动发送

3.数据库集成

import sqlite3
# 将转换记录存入数据库

4.日志监控系统

import logging
logging.basicConfig(filename='converter.log')

以上就是Python3脚本实现Excel与TXT的智能转换的详细内容,更多关于Python3 Excel转TXT的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文