项目需求客户要求把表格数据下载时,备份到数据库

项目需求客户要求把表格数据下载时,备份到数据库

三个步骤:另存,改编码,导数据库

先把 wps 表格文件 另存为 csv,然后修改编码为 UTF8
如果是 csv 文件,那么可以把它在转换为 txt 文件。因为直接的转换会导致为空格分隔符。而此时就是逗号分隔,然后直接可以导入数据库。

也可以通过代码实现

#!/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @virtualenv:workon
# @contact: contact information
# @Desc:Code descripton
__author__ = '未昔/AngelFate'
__date__ = '2019/9/12 17:01'
import pymysql
import pandas as pd

data = pd.read_csv(r'E:\RPA\new_SPDB\RPA_Result\result2.csv')
data['开户'] = pd.to_datetime(data['核准'])
data['核准'] = pd.to_datetime(data['核准'])
data['销户'] = pd.to_datetime(data['销户'])
data['到期'] = pd.to_datetime(data['到期'])
data.fillna('',inplace=True)
print(data.dtypes)
print(data.head())

data_row = 1  # 记录数据
for branch_name,branch_code,organization_name,organization_number,customer_number,customer_name,account_number,account_name,opening_date,approval_date,close_date,due_date,currency,course_number,business_code,currency_identification,account_status,account_attributes,account_safe,account_nature,error_cause in (data['分行名称'],data['分行代码'],data['机构名称'],data['机构号'],data['客户号'],data['客户名称'],data['账号'],data['账户名称'],data['开户'],data['核准'],data['销户'],data['到期'],data['币种'],data['科目号'],data['业务代号'],data['通兑标识'],data['账户状态'],data['账户属性'],data['外管局账户性质'],data['账户性质'],data['错误原因']):
    print(data_row,branch_name,branch_code,organization_name,organization_number,customer_number,customer_name,account_number,account_name,opening_date,approval_date,close_date,due_date,currency,course_number,business_code,currency_identification,account_status,account_attributes,account_safe,account_nature,error_cause)
    data_row+=1

    # 打开数据库连接
    conn = pymysql.Connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='',
        db='film',  # 数据库名称
        charset='utf8'
    )
    # 使用cursor()方法获取操作游标
    cursor = conn.cursor()

    try:
        dataList = [data_row,branch_name,branch_code,organization_name,organization_number,customer_number,customer_name,account_number,account_name,opening_date,approval_date,close_date,due_date,currency,course_number,business_code,currency_identification,account_status,account_attributes,account_safe,account_nature,error_cause]
        insertsql = "INSERT INTO spdb_account(data_row,branch_name,branch_code,organization_name,organization_number,customer_number,customer_name,account_number,account_name,opening_date,approval_date,close_date,due_date,currency,course_number,business_code,currency_identification,account_status,account_attributes,account_safe,account_nature,error_cause) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        cursor.execute(insertsql, dataList)
        conn.commit()
        print('okok')
    except Exception as e:
        print(e)
        conn.rollback()
    cursor.close()
    # 关闭数据库连接
    conn.close()