学校网站建设招标方案,网站建设实训小组总结,营销型单页面网站,网页设计作业下载近日完成一个交办任务#xff0c;从excel表读取数据#xff0c;根据ID在数据库表匹配相应的记录#xff0c;并回填至excel表里。我使用的工具是python。下面记录下相应的模块。
一、从excel表读取数据
import pandas as pd
import numpy as npdef read_excel():path 从excel表读取数据根据ID在数据库表匹配相应的记录并回填至excel表里。我使用的工具是python。下面记录下相应的模块。
一、从excel表读取数据
import pandas as pd
import numpy as npdef read_excel():path 导出模板.xlsxsheetname Sheet1df pd.read_excel(path, sheet_namesheetname,index_colNone, na_values[NA]))columns df.columns #读取标题rows df.values #读取数据集 列表listrows np.array(rows) #需要切片转换np.array# print(rows[:, 0]) #切片列return rows
二、据ID在数据库表匹配相应的记录
# coding:utf-8
import pandas as pd
import pymysqlclass order:def __init__(self):self.cn pymysql.connect(hostXX.XX.XX.XX,userroot,password123456,databasedatabase)#使用read_sql函数来读取数据也可以有其他写法只是这种更简洁def findById(self, sql):df pd.read_sql(sql, conself.cn)return df.values.tolist()#这种写法也可以只是不够简洁def update_sql(self, rows):sql update table set c_iserr%s where c_id%scur self.cn.cursor()cur.executemany(sql, rows)self.cn.commit()self.cn.close()# df是DataFrame格式 table_name是写入的目标表名name 指定的是目标数据库表con 与数据库链接的方式推荐使用sqlalchemy的engine类型if_exists 当数据库中已经存在数据表时对数据表的操作有replace替换、append追加fail则当表存在时提示ValueErrorindex 对DataFrame的index索引的处理True时索引也将作为数据写入数据表chunsize 整数一次写入数据时的数据行数量def write_sql(self, df, table_name):df.to_sql(nametable_name, conself.cn,if_existsappend, indexFalse, chunksize1000)
其中由于调用接口还需要使用request模块
import requests
import datatime
import jsondef getInterface(url):riqi datetime.datetime.now().strftime(%Y/%m)text requests.get(url).text#若返回的是字符串还需json.loads转为dict格式。return json.loads(text)# 数据demo如下
# {message: OK, success: true, data: [{}]}
三、回填至excel表里
以上新建class类就可以在接下来的函数调用它。
if __name__ __main__:sql select * from table where id%sdb order()#此处rows是第一点返回的列表listfor row in rows:result db.findById(sql % (row[0]))#需要切片转换np.arrayresult np.array(result)#todo 逻辑写入......#再一次将rows转换为dataframedf pd.DataFrame(rows, columnscolumns)# print(df.head())pd.DataFrame(df).to_excel(path, sheet_namesheetname, indexFalse)
总结一个小任务涉及到np.array的切片panda操作sql和exceldataframe和list之间转换datatime和字符串之间转换json和字符串之间的转换等知识。
感慨python的基础知识需要扎实才行。