简体   繁体   English

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

[英]Converting all worksheets in an Excel workbook to csv format

My Excel document my.xlsx has two Sheets named Sheet1 and Sheet2 .我的 Excel 文档my.xlsx有两个名为Sheet1Sheet2 的工作表。 I want to convert all worksheets to csv format using xlsx2csv .我想使用xlsx2csv将所有工作表转换为csv格式。 I used the following commands:我使用了以下命令:

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

Any help, please.任何帮助,请。

I have not used xlsx2csv before but why don't we try pandas .我以前没有使用过xlsx2csv但我们为什么不尝试pandas

Your requirement can be solved like this:您的要求可以这样解决:

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)

You can do something as the follows:您可以执行以下操作:

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)

Xlsx2csv python implementation: Xlsx2csv python 实现:
Could only execute Xlsx2csv with sheetid parameter.只能使用 sheetid 参数执行 Xlsx2csv。 In order to get sheet names and ids, get_sheet_details was used.为了获取工作表名称和 ID,使用了get_sheet_details
csvfrmxlsx creates csv files for each sheet in csv folder under parent directory. 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python:创建excel工作簿并将csv文件转储为工作表 - python: creating excel workbook and dumping csv files as worksheets 如何将Excel工作簿中的所有工作表另存为一个文本文件? - How to save all worksheets in Excel workbook as one text file? Python 中的所有 my.csv 文件都将转换为 excel 文件 df.to_csv('stock_dfs/{}.csv'.format(ticker) - All my .csv files in Python are converting to excel files df.to_csv('stock_dfs/{}.csv'.format(ticker)) 如何使用 Xlwings 和 Python 合并同一个 Excel 工作簿中的所有工作表 - How to Merge all worksheets within the same excel workbook using Xlwings & Python Python/Openpyxl:将工作簿中所有 excel 工作表中的单元格 A1 更改为等于工作表选项卡的名称 - Python/Openpyxl: change cell A1 in all excel worksheets within a workbook to equal the name of the worksheet tab 如何将多个 excel 工作簿组合成具有多个工作表的单个工作簿 - How to combine multi excel workbook into single workbook with multiple worksheets 冻结工作簿中所有工作表的第一行(Python) - Freeze first row of all worksheets in workbook (Python) 将文本格式的固定宽度表格转换为dataframe/excel/csv - Converting a table of fixed width in text format into dataframe/excel/csv 使用 Pandas to pd.read_excel() 为同一工作簿的多个工作表 - Using Pandas to pd.read_excel() for multiple worksheets of the same workbook 如何将 Excel 工作表保存在单个工作簿中作为工作簿及其数据 - How can I save Excel worksheets in a single workbook as workbooks with their data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM