#Excel到CSV的转换程序
import openpyxl, os, csv
#遍历文件夹中的文件,跳过非excel文件
os.chdir("F:\\python_work\\automate_online-materials\\excelSpreadsheets")
print("loop through the excel file in thr directory...")
for filename in os.listdir('.'):
if not filename.endswith('.xlsx'):
continue
#提取不带后缀的文件名,并加载excel文件放在workbook中
first_filename = os.path.splitext(filename)[0]
print("loading the excel file...")
wb = openpyxl.load_workbook(filename)
#获取Excel文件中表格的信息
for sheetname in wb.sheetnames:
print("get the info in the file...")
sheet = wb[sheetname]
#创建CSV文件名字符串,并创建csv.writer对象
csv_name = first_filename + '_' + sheetname +'.csv'
csv_file_obj = open(os.path.join(os.path.abspath('.'), 'csv_directory', csv_name), 'w', newline = '')
csv_writer = csv.writer(csv_file_obj)
#遍历表的每一行
for row_num in range(1, sheet.max_row+1):
#遍历一行中的所有单元格,并添加到列表中
row_data = []
for column_num in range(1, sheet.max_column+1):
row_data.append(sheet.cell(row_num, column_num).value)
#将列表的内容写进csv.writer对象中
csv_writer.writerow(row_data)
csv_file_obj.close()
print("Done.")
python-从Excel到CSV的转换程序
最新推荐文章于 2023-10-17 10:03:03 发布