'''寫入excel文件''' import xlsxwriter # todo 創建excel文件 xl = xlsxwriter.Workbook(r'D:\testfile\test.xlsx') # todo 添加sheet sheet = xl.add_worksheet('sheet1') # todo 往單元格cell添加數據,索引寫入 sheet.write_string(0,0,'username') # todo 位置寫入 sheet.write_string('B1','password') # todo 設置單元格寬度大小 sheet.set_column('A:B',30) # todo 關閉文件 xl.close()
import os import openpyxl def get_file_name(file_dir): ''' 獲取指定目錄下所有文件名稱 :param file_dir:指定目錄 :return:返回文件名列表 ''' for root, dirs, files in os.walk(file_dir): # return root#當前目錄路徑 # return dirs#當前路徑下所有子目錄 return files # 當前路徑下所有非目錄子文件 def class_file_name(file_dir, file_type): ''' 獲取指定文件夾下的指定文件類型名稱 :param file_dir:指定目錄 :param file_type: :return:返回文件名列表 ''' ls = [] f = [] for root, dirs, files in os.walk(file_dir): for file in files: if os.path.splitext(file)[1] == file_type: ls.append(os.path.join(root, file)) f.append(file) return f def output2excel(file_dir): ''' 把文件夾下的文件名稱輸出到文件目錄 :param file_dir: 文件目錄 :return: ''' # 獲取文件目錄下所有文件名,存入data列表 data = get_file_name(file_dir) # 把data輸出到該目錄下,並以目錄名保存為excel格式 wb = openpyxl.Workbook() sheet = wb.active # 設置表名為文件目錄名 sheet.title = file_dir for i in range(1, len(data) + 1): sheet['A{}'.format(i)] = data[i - 1] if file_dir == '': file_dir = '當前目錄' wb.save('{0}/{0}.xlsx'.format(file_dir)) file_dir = '本科' output2excel(file_dir) 原文鏈接:https://blog.csdn.net/wz_spinoza/java/article/details/88788220