python 读写excel
读取excel中的内容
def get_app_service():
df = pd.read_excel("test.xlsx",sheet_name='test') #读取excel对应的sheet
data = list(df['service']) #读取一列
# print(data)
return data
写数据到excel,生成新的excel
writer = pd.ExcelWriter("test.xlsx")
df = pd.DataFrame(data_res) #data_res数据[[1,2,3],[1,2,3]]
df.columns = title
df.to_excel("test.xlsx",sheet_name=sheet_name,index=False)
writer.save()
写数据到已存在的excel,不生成新的excel
df = pd.DataFrame(data_res)
df.columns = title
file_name = 'test.xlsx'
try:
wb = load_workbook(file_name)
ws = wb[sheet_name]
wb.remove(ws)
wb.save(file_name)
with pd.ExcelWriter(file_name, mode='a') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
except Exception as e:
with pd.ExcelWriter(file_name, mode='a') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)