【Python】将Excel内容转为多个txt文件保存

import xlrd
import os

data_dir = './data/predict'
def read_excel():
    # 打开文件
    workbook = xlrd.open_workbook('333.xlsx')

    # 根据sheet索引或者名称获取sheet内容
    sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始

    # sheet的名称,行数rowNum,列数colNum
    print(sheet1.name.encode('utf-8'),sheet1.nrows,sheet1.ncols)
    for rowNum in range(1,sheet1.nrows ):      #遍历1到所有行 (因为0行是表头)
        tmp=""
        colNum = 6   #我需要的是第七列
        #for colNum in range(0,sheet1.ncols):    #遍历所有列,0对应第一列
        if sheet1.cell(rowNum ,colNum ).value!=None:
            tmp = str(sheet1.cell(rowNum ,colNum ).value)
        filename = os.path.join(data_dir) + str(rowNum) + '.txt' #将第七列每个单元格
                                                        # 内容都存入一个新的txt文件中
        f = open(filename, 'w', encoding='utf-8')
        f.write(tmp)


if __name__ == '__main__':
    read_excel()

你可能感兴趣的:(【Python】将Excel内容转为多个txt文件保存)