2023年3月25日星期六

Python的Excel操作


Excel文件的读取

单一Sheet文件读取

import pandas as pd
data = pd.read_excel("new_excel.xlsx")

多个Sheet文件读取

import pandas as pd
data = pd.read_excel("new_excel_2",sheet_name='sheet_2')

read_excel()函数能够读取Excel2003(.xls)Excel2007(.xlsx)两种类型的文件

不指定sheet_name时默认读取第一张表的数据

读取制定列数据室使用usecols,如:

col_list = ['id', 'Age']或col_list = [1, 3]

data = pd.read_excel(excel_file, usecols=col_list)

Excel文件的写入

写入单一Sheet

import pandas as pd
data.to_excel('sample.xlsx', sheet_name='sheet1', index=False)

写入多个Sheet

import pandas as pd
writefile='E:\\sample.xlsx'
with pd.ExcelWriter(writefile) as writer:
   data.to_excel(writer, sheet_name = 'sheet1', index=False)
   data_1.to_excel(writer,sheet_name='sheet2',index=False)

wirtefile:需要写入文件路径

data:类型为dataframe的数据

sheet_name:需要写入的sheet名

index = False:写入是不写入行索引

没有评论: