Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将Excel工作簿中的所有工作表转换为csv格式_Python_Excel - Fatal编程技术网

Python 将Excel工作簿中的所有工作表转换为csv格式

Python 将Excel工作簿中的所有工作表转换为csv格式,python,excel,Python,Excel,我的Excel文档My.xlsx有两张表,分别名为Sheet1和Sheet2。我想使用xlsx2csv将所有工作表转换为csv格式。我使用了以下命令: from xlsx2csv import * xlsx2csv my.xlsx convert.csv File "<stdin>", line 1 xlsx2csv my.xlsx convert.csv ^ SyntaxError: invalid syntax x2c -a my.xlsx

我的Excel文档
My.xlsx
有两张表,分别名为Sheet1Sheet2。我想使用
xlsx2csv
将所有工作表转换为
csv
格式。我使用了以下命令:

from xlsx2csv import *
xlsx2csv my.xlsx convert.csv
File "<stdin>", line 1
    xlsx2csv my.xlsx convert.csv
              ^
SyntaxError: invalid syntax

x2c -a my.xlsx my1.csv
  File "<stdin>", line 1
    x2c -a my.xlsx my1.csv
            ^
SyntaxError: invalid syntax
从xlsx2csv导入*
xlsx2csv my.xlsx convert.csv
文件“”,第1行
xlsx2csv my.xlsx convert.csv
^
SyntaxError:无效语法
x2c-a my.xlsx my1.csv
文件“”,第1行
x2c-a my.xlsx my1.csv
^
SyntaxError:无效语法

任何帮助,请。

我以前没有使用过
xlsx2csv
,但是我们为什么不试试
pandas

您的需求可以这样解决:

import pandas as pd
for sheet in ['Sheet1', 'Sheet2']:
    df = pd.read_excel('my.xlsx', sheetname=sheet)
    df.to_csv(sheet + '_output.csv', index=False)

您可以执行以下操作:

import pandas as pd

xls_file = pd.ExcelFile('<path_to_your_excel_file>')
sheet_names = xls_file.sheet_names

for sheet in sheet_names:
    df = xls_file.parse(sheet)
将熊猫作为pd导入
xls_file=pd.ExcelFile(“”)
图纸\u名称=xls\u文件。图纸\u名称
对于图纸名称中的图纸:
df=xls_file.parse(表)

Xlsx2csv python实现:
只能使用sheetid参数执行Xlsx2csv。为了获取工作表名称和ID,使用了。
csvfrmxlsx为父目录下csv文件夹中的每个图纸创建csv文件

import pandas as pd
from pathlib import Path


def get_sheet_details(filename):
    import os
    import xmltodict
    import shutil
    import zipfile
    sheets = []
    # Make a temporary directory with the file name
    directory_to_extract_to = (filename.with_suffix(''))
    os.mkdir(directory_to_extract_to)
    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(filename, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()
    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = directory_to_extract_to / 'xl' / 'workbook.xml'
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],  # can be sheetId for some versions
                'name': sheet['@name']  # can be name
            }
            sheets.append(sheet_details)
    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets


def csvfrmxlsx(xlsxfl, df):  # create csv files in csv folder on parent directory
    from xlsx2csv import Xlsx2csv
    for index, row in df.iterrows():  
        shnum = row['id']
        shnph = xlsxfl.parent / 'csv' / Path(row['name'] + '.csv')  # path for converted csv file
        Xlsx2csv(str(xlsxfl), outputencoding="utf-8").convert(str(shnph), sheetid=int(shnum))  
    return


pthfnc = 'c:/xlsx/'
wrkfl = 'my.xlsx'
xls_file = Path(pthfnc + wrkfl)
sheetsdic = get_sheet_details(xls_file)  # dictionary with sheet names and ids without opening xlsx file
df = pd.DataFrame.from_dict(sheetsdic)
csvfrmxlsx(xls_file, df)  # df with sheets to be converted

谢谢@Kelvin的回答。如果您给出不使用图纸名称的解决方案,我们将不胜感激。B/c我的xlsx非常大,使用Excel不容易打开,因此不知道手头的图纸名称。Thanks@MYaseen208是的,绝对是。您可以这样做:
my_file=pd.ExcelFile('my.xlsx')
然后循环遍历所有工作表:
对于my_file.sheet\u name中的工作表:df=pd.read\u excel('my.xlsx',sheetname=sheet)