对一文件路径下的excel表格生成导航表

对一文件路径下的excel表格生成导航表_第1张图片

对一文件路径下的excel表格生成导航表_第2张图片

#coding:utf8
import os
import os.path
import xlwt
import xlrd
#  --- 获取当前路径 ---
filePath = os.getcwd()

targetPath = filePath + '/Z_GuideExcel.xls'
#  --- 创建表格 ---
getWordExcel=xlwt.Workbook()
#  --- 创建 Sheet ---
getTable = getWordExcel.add_sheet('ConfigExcel',cell_overwrite_ok = True)
#  --- 行数 ---
index = 0
#  --- 遍历相应路径下的 parent :父目录 dirnames 所有文件夹 filenames 所有文件名 ---

testFile = os.listdir(filePath)
index = 0
for item in testFile:
    if not item.endswith('.xls'):
        continue
    if item == 'Z_GuideExcel.xls':
        continue
    totalFilePath = os.path.join('%s%s' % (filePath+'\\', item))
    # print totalFilePath.decode('gbk')  # .decode('gbk')是解决中文显示乱码问题
    fileInfo02 = xlrd.open_workbook(totalFilePath)
    index2 = 1
    getTable.write(index, 0, item)
    getTable.col(0).width = 120 * 50
    for item2 in fileInfo02.sheet_names():
        # print  item2
        # --- 写入表格第一列 ---
        # print item2 + '--- ' + str(index2)
        getTable.write(index, index2, item2)
        getTable.col(index2).width = 120 * 50
        #  --- 行数自增 1 ---
        index2 += 1
    index += 1

# for parent,dirnames,filenames in os.walk(filePath):
#     #  --- 遍历所有文件 ---
#     index = 0
#     print  'z这是第一层'
#     for filename in filenames:
#         #  --- 设置/获取 当前文件父目录 ---
#         totalFilePath=os.path.join(parent,filename)
#         #  --- 获取后缀为 .cs 或者 .txt的文件 ---
#         if filename.endswith('.xls'):
#             if filename == 'TestExcel.xls':
#                 continue
#             print  filename+'---'+str(index)
#             #  --- 获取文件全路径 ---
#             totalFile=os.path.abspath(totalFilePath)
#             #  --- 打开读取文件 'r' 为读取  'w' 为写入
#             # fileInfo02=open(totalFilePath,'r')
#             fileInfo02 = xlrd.open_workbook(totalFilePath)
#             index2 = 1
#             getTable.write(index, 0, filename)
#             for item in fileInfo02.sheet_names():
#                 # --- 写入表格第一列 ---
#                 print item +'--- '+str(index2)
#                 getTable.write(index, index2, item)
#                 index2 += 1
#                 #  --- 行数自增 1 ---
#         index += 1

#  --- 判断该表格是否存在 ---
if os.path.isfile(targetPath):
    os.remove(targetPath)
getWordExcel.save(targetPath)

当前只处理(.xls)后缀的文件,可自己拓展。

注:文件路径不要包含中文。

你可能感兴趣的:(Python)