如题,请问 有能提取excle 内工作表名称 ,然后生成TXT或者其他文本文件 的软件吗?
具体说下需求,我给你写一个
以下为 ChatGPT 生成,我没环境就没试
from openpyxl import load_workbook
# 输入Excel文件路径
excel_file_path = "your_excel_file.xlsx"
# 打开Excel文件
workbook = load_workbook(filename=excel_file_path, read_only=True)
# 创建一个空列表来保存工作表名称
sheet_names = []
# 遍历工作表并保存名称
for sheet_name in workbook.sheetnames:
sheet_names.append(sheet_name)
# 关闭Excel文件
workbook.close()
# 将工作表名称写入txt文件
txt_file_path = "sheet_names.txt"
with open(txt_file_path, "w") as txt_file:
for name in sheet_names:
txt_file.write(name + "\n")
print("Sheet names have been saved to", txt_file_path)
确保将 "your_excel_file.xlsx" 替换为你的实际 Excel 文件路径,并且文件名 "sheet_names.txt" 可以更改为你想要保存的文本文件名。
就是我现在电脑有很多excle ,每个excle内有好多不同的工作表,现在的需求是将这些工作表的名称提取出来 到外部TXT文件或其他文本文件内。
谢谢 大佬哈
谢谢了,我试下
Excle ? Excel!
1 个赞
随便写了个,简单测试了下,应该没bug吧
使用方法:直接拖入文件/文件夹到exe上,程序会自动生成一个txt
import os
import sys
from typing import Tuple
from openpyxl import load_workbook
import xlrd
def _get_names_xlsx(path):
workbook = load_workbook(filename=path, read_only=True)
sheet_names = workbook.sheetnames
workbook.close()
return sheet_names
def _get_names_xls(path):
workbook = xlrd.open_workbook(path)
sheet_names = workbook.sheet_names()
return sheet_names
def get_dirs_files(folder: str) -> Tuple[list, list]:
"""获取一个文件夹中所有的文件列表,文件夹列表
:return: 两个list,所有文件夹列表,所有文件列表"""
dirs = []
files = []
for dirpath, dirnames, filenames in os.walk(folder):
for k in dirnames:
dirpath_join = os.path.normpath(os.path.join(dirpath, k))
dirs.append(dirpath_join)
for j in filenames:
filepath_join = os.path.normpath(os.path.join(dirpath, j))
files.append(filepath_join)
return dirs, files
paths = sys.argv[1:]
xlsx_files = []
xls_files = []
for path in paths:
if os.path.isfile(path):
if path.lower().endswith('.xls'):
xls_files.append(path)
elif path.lower().endswith('.xlsx'):
xlsx_files.append(path)
elif os.path.isdir(path):
_, child_paths = get_dirs_files(path)
for path in child_paths:
if os.path.isfile(path):
if path.lower().endswith('.xls'):
xls_files.append(path)
elif path.lower().endswith('.xlsx'):
xlsx_files.append(path)
print(xlsx_files)
print(xls_files)
for xlsx in xlsx_files:
names = _get_names_xlsx(xlsx)
with open('工作表名称汇总.txt', 'a') as txt_file:
txt_file.write('\n' + xlsx + '\n')
for name in names:
txt_file.write(name + '\n')
for xls in xls_files:
names = _get_names_xls(xls)
with open('工作表名称汇总.txt', 'a') as txt_file:
txt_file.write('\n' + xls + '\n')
for name in names:
txt_file.write(name + '\n')
1 个赞
然后需求就变成遍历指定目录下所有子目录的excel作txt了
用Power Query,EXCEL自己就能搞定
遍历指定目录下所有子目录的excel作txt :
sheetTool
谢谢,解决了,没有报错