用Python将Excel转换为CSV |
您所在的位置:网站首页 › 批判性观点的英语怎么说怎么写 › 用Python将Excel转换为CSV |
用Python将Excel转换为CSV
在这篇文章中,我们将处理将Excel(.xlsx)文件转换为.csv的问题。在Excel中主要有两种格式。 (*.xlsx) :Excel Microsoft Office Open XML Format 电子表格文件。 (*.xls) :Excel电子表格(Excel 97-2003工作簿)。让我们考虑一个购物商店的数据集,其中有关于客户序列号、客户姓名、客户ID和产品成本的数据存储在Excel文件中。 在这里查看所有使用过的文件。 # importing pandas as pd import pandas as pd # read an excel file and convert # into a dataframe object df = pd.DataFrame(pd.read_excel("Test.xlsx")) # show the dataframe df输出 : 现在,让我们看看将Excel文件转换为CSV文件的不同方法: 方法一:使用pandas库将Excel文件转换成CSV文件Pandas是一个开源的软件库,为Python编程语言的数据操作和分析而建立。它在数据结构和操作方面提供了各种功能,用于处理数字表和时间序列。它可以读取、过滤和重新排列小型和大型数据集,并以一系列格式输出,包括Excel、JSON、CSV。 对于读取excel文件,使用read_excel()方法,并将数据框转换成CSV文件,使用pandas的to_csv()方法。 代码: #importing pandas as pd import pandas as pd # Read and store content # of an excel file read_file = pd.read_excel ("Test.xlsx") # Write the dataframe object # into csv file read_file.to_csv ("Test.csv", index = None, header=True) # read csv file and convert # into a dataframe object df = pd.DataFrame(pd.read_csv("Test.csv")) # show the dataframe df输出: xlrd是一个库,主要目的是读取excel文件。 csv是一个库,主要目的是读取和写入csv文件。 代码: # import all required library import xlrd import csv import pandas as pd # open workbook by sheet index, # optional - sheet_by_index() sheet = xlrd.open_workbook("Test.xlsx").sheet_by_index(0) # writer object is created col = csv.writer(open("T.csv", 'w', newline="")) # writing the data into csv file for row in range(sheet.nrows): # row by row write # operation is perform col.writerow(sheet.row_values(row)) # read csv file and convert # into a dataframe object df = pd.DataFrame(pd.read_csv("T.csv")) # show the dataframe df输出: openpyxl是一个读/写Excel 2010 xlsx/xlsm/xltx/xltm文件的库。它诞生于缺乏从Python原生读/写Office Open XML格式的现有库。 代码: # importe required libraries import openpyxl import csv import pandas as pd # open given workbook # and store in excel object excel = openpyxl.load_workbook("Test.xlsx") # select the active sheet sheet = excel.active # writer object is created col = csv.writer(open("tt.csv", 'w', newline="")) # writing the data in csv file for r in sheet.rows: # row by row write # operation is perform col.writerow([cell.value for cell in r]) # read the csv file and # convert into dataframe object df = pd.DataFrame(pd.read_csv("tt.csv")) # show the dataframe df输出: |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |