python-从Excel到CSV的转换程序

#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.")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值