如何从* .xlsm中提取工作表并将其另存为Python中的* .csv? [英] How to extract sheet from *.xlsm and save it as *.csv in Python?

查看:129
本文介绍了如何从* .xlsm中提取工作表并将其另存为Python中的* .csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个* .xlsm文件,其中有20张纸. 我想将几张纸单独保存为* .csv(格式丢失是可以的). 已经尝试过xlrd-xlwt和win32com库,但无法通过. 谁能提供一个使用Python进行上述处理的代码段?我还有其他python依赖项,因此没有其他语言可以使用. 谢谢

I have a *.xlsm file which has 20 sheets in it. I want to save few sheets as *.csv (formatting loss is fine) individually. Already tried xlrd-xlwt and win32com libraries but could not get through. Can anybody please provide a code snippet which does the above processing in Python? I have other python dependencies so no other language would work. Thanks

推荐答案

xlrd 应该可以正常工作在xlsm文件上也是如此.我用一个随机的xlsm文件测试了代码,效果很好.

xlrd should work fine on xlsm files as well. I tested the code with a random xlsm file, and it worked perfectly.

import csv
import xlrd

workbook = xlrd.open_workbook('test.xlsx')
for sheet in workbook.sheets():
    with open('{}.csv'.format(sheet.name), 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(sheet.row_values(row) for row in range(sheet.nrows))


如果您编码有问题,请尝试以下代码:


If you've encoding issues, try the code below:

import csv
import xlrd

workbook = xlrd.open_workbook('test.xlsm')
for sheet in workbook.sheets():
    if sheet.name == "Sheet_name_from_xlsm_file":
        with open('{}.csv'.format(sheet.name), 'wb') as f:
            writer = csv.writer(f)
            for row in range(sheet.nrows):
                out = []
                for cell in sheet.row_values(row):
                    try:
                        out.append(cell.encode('utf8'))
                    except:
                        out.append(cell)
                writer.writerow(out)

这篇关于如何从* .xlsm中提取工作表并将其另存为Python中的* .csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆