zoukankan      html  css  js  c++  java
  • Python导入excel数据到sqlite;

    Python导入excel数据到sqlite;

    # coding=utf-8
    import xlrd
    import sqlite3
    import os
    import uuid
    
    def insert_data_to_db(path):
        wb = xlrd.open_workbook(path)
        print(wb.sheet_names())
        sheet = wb.sheets()[0]
        nrows = sheet.nrows
        # 获取任务行里索引
        begin_index = 0
        end_index = begin_index
        for i in range(nrows):
            col_value = sheet.row(i)[1].value
            if(begin_index == 0 and col_value == "责任人"):
                begin_index = i + 1
                end_index = begin_index
            if(begin_index != 0 and col_value == ""):
                end_index = i
                break
        print(begin_index)
        print(end_index)
    
        # 检查创建数据库
        db_path = "zb.db"
        is_db_exist = os.path.exists(db_path)
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        if not is_db_exist:
            conn.execute('''CREATE TABLE IF NOT EXISTS Tasks(
                Id varchar PRIMARY KEY,
                Name varchar,
                Task varchar,
                PercentageTask varchar,
                BeginTime datetime,
                EndTime datetime,
                Memo varchar,
                FileName varchar)''')
            conn.commit()
    
        # 获取文件名
        (_file_path, file_name) = os.path.split(path)
    
        sql = '''INSERT OR REPLACE INTO Tasks 
            (Id,Name,Task,PercentageTask,BeginTime,EndTime,Memo,FileName) VALUES (?,?,?,?,?,?,?,?)'''
    
        # 遍历内容插入数据库
        for i in range(begin_index, end_index):
            col_id = str(uuid.uuid1())
            col_name = sheet.row(i)[1].value
            col_task = sheet.row(i)[2].value
            col_percentage_task = sheet.row(i)[3].value
            col_begin_time = sheet.row(i)[4].value
            col_end_time = sheet.row(i)[5].value
            col_memo = sheet.row(i)[6].value
            cursor.execute(sql, (col_id, col_name, col_task, col_percentage_task,
                                 col_begin_time, col_end_time, col_memo, file_name))
        conn.commit()
    
    
    def main():
        file_dir = "zb"
        for _root, _dirs, files in os.walk(file_dir):
            for file in files:
                insert_data_to_db(file_dir+"/"+file)
    
    
    main()
  • 相关阅读:
    .NET中栈和堆的比较 #1
    Asp Interview Questions and Answers
    c#缓存介绍(转)
    [转]Post和Get的区别(兼谈页面间传值的方式)
    .NET垃圾回收机制 转
    zoj 3008 3010
    zoj 2912 Average distance
    TinyMCE,强大的网页编辑器插件
    zoj 3587 Marlon's String
    SOJ和FOJ的比赛
  • 原文地址:https://www.cnblogs.com/guanglin/p/14107287.html
Copyright © 2011-2022 走看看