美文网首页
excel表数据的导入导出

excel表数据的导入导出

作者: Gary134 | 来源:发表于2019-04-09 00:28 被阅读0次

    从excel表导入MySQL数据库

    import xlrd
    import pymysql
    
    
    # 写入excel表数据
    def insert_data():
        data = xlrd.open_workbook("excel/test.xlsx")
        sheet_names = data.sheet_names()
        # print(sheet_names)
        # 连接数据库
        db = pymysql.connect(host='localhost', user='root', passwd='123456',
                             db='excel', charset='utf8')
        cursor = db.cursor()
        for i in range(len(sheet_names)):
            # 当前sheet的名字
            table_name = sheet_names[i]
            # 当前的sheet
            now_table = data.sheet_by_index(i)
            # 获得当前sheet的列数就是属性数
            cols_num = now_table.ncols
            # 获得当前表格的行数,就是有多少的数据量
            rows_num = now_table.nrows
            attrs = now_table.row_values(0)
            # 判断表格是否存在
            flag = cursor.execute("show tables like '%s';" % table_name)
            # print(flag)
            # 表存在
            if flag:
                print("-------")
                # 将当前的sheet插入到数据库
                for j in range(1, rows_num):
                    row_value = now_table.row_values(j)
                    # 处理要插入的数据,把非字符串的数据转换成字符串类型,同时将字符串变成 sql语句需要的类型
                    for k in range(1, len(row_value)):
                        ctype = now_table.cell(j, k).ctype
                        # print('ctype', ctype)
                        # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                        if ctype == 2 and row_value[k] % 1 == 0:
                            tmp = int(row_value[k])
                            row_value[k] = str(tmp)
                        c = row_value[k]
                        row_value[k] = "'" + c + "'"
                    # print(row_value)
                    sql = "insert into %s(%s) values(%s);" % (table_name, ','.join(attrs[1:]), ','.join(row_value[1:]))
                    cursor.execute(sql)
                    db.commit()
            else:
                # 为sheet建表
                cursor.execute(f"create table {table_name} (id int primary key auto_increment);")
                db.commit()
                for l in range(1, cols_num):
                    cursor.execute(f"alter table {table_name} add column {attrs[l]} varchar(200);")
                    db.commit()
                # 将当前的sheet插入到数据库
                for j in range(1, rows_num):
                    row_value = now_table.row_values(j)
                    # 处理要插入的数据,把非字符串的数据转换成字符串类型,同时将字符串变成 sql语句需要的类型
                    for k in range(1, len(row_value)):
                        ctype = now_table.cell(j, k).ctype
                        print('ctype', ctype)
                        # ctype: 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                        if ctype == 2 and row_value[k] % 1 == 0:
                            tmp = int(row_value[k])
                            row_value[k] = str(tmp)
                        c = row_value[k]
                        row_value[k] = "'" + c + "'"
                    sql = "insert into %s(%s) values (%s);" % (table_name, ','.join(attrs[1:]), ','.join(row_value[1:]))
                    cursor.execute(sql)
                    db.commit()
        db.close()
    
    
    if __name__ == '__main__':
        insert_data()
    

    从MySQL数据库写入excel表

    import xlwt
    import pymysql
    import os
    import datetime
    
    
    # 从数据库读取数据写入excel,生成xls or xlsx格式文件
    def table_export_to_xls(sql):
        table_name = 'sheet1'
        # 连接数据库
        db = pymysql.connect(host='localhost', user='root', passwd='123456',
                             db='excel', charset='utf8')
        cursor = db.cursor()
        cursor.execute(sql)
        # 重置游标位置
        cursor.scroll(0, mode='absolute')
        # 搜取所有的结果
        results = cursor.fetchall()
        # print(result)
        # 获取属性名
        attrs = cursor.description
        print(attrs)
    
        workbook = xlwt.Workbook()
        sheet1 = workbook.add_sheet(table_name, cell_overwrite_ok=True)
        # 写入表格的属性值
        for i in range(1, len(attrs)):
            sheet1.write(0, i-1, attrs[i][0])
        # 将数据库的数据导入表格
        row = 1
        col = 0
        for row in range(1, len(results)+1):
            for col in range(0, len(attrs)-1):
                sheet1.write(row, col, results[row-1][col+1])
        # 保存路径
        now_path = os.path.dirname(__file__)
        print(now_path)
        file_path = os.path.join(now_path, 'excel')
        print(file_path)
        export_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        file_name = 'test-{0}.xlsx'.format(export_time)
        workbook.save(os.path.join(file_path, file_name))
    
        if os.path.isfile(os.path.join(file_path, file_name)):
            print('数据库重成功导出数据!')
            return {'path': file_path, 'name': file_name}
        else:
            print('导出失败!')
            return 'error'
    
    
    if __name__ == '__main__':
        sql = "select * from sheet1"
        table_export_to_xls(sql)
    

    PostgreSQL可参考:

    https://blog.csdn.net/huangmengfeng/article/details/81005505
    

    相关文章

      网友评论

          本文标题:excel表数据的导入导出

          本文链接:https://www.haomeiwen.com/subject/acfviqtx.html