excel导入数据与数据库对接操作

1.接口excel

class csv_input:

    """导入文件需要写入文件名
    sheet_digit为输入框参数

    """
    def __init__(self, csv_name, sheet_digit=1):
        self.data = xlrd.open_workbook('%s' % csv_name + ".xlsx")
        self.sheet_digit = sheet_digit
        self.write_csv()
        # print("self.data", self.data)
        # content_list = self.write_csv()

    def write_csv(self):

        for k in range(1):  # 这range(self.sheet_digit)
            table = self.data.sheets()[k]
            rows = table.nrows
            for i in range(int(rows)):
                if i == 0 or i == 1:
                    continue
                else:
                    content = table.row_values(i)
                    d = 0
                    for i in content:
                        if type(i) != str:
                            content[d] = str(i)
                        d += 1
                    sqlit_handle().edit_add(content, k)
        sqlit_handle().conn.close()

 

2. sqlite数据库写入excel、导出excel数据 

重点:(1)注意pycharm中的database可视化管理,必须是DDL的数据库才可以与代码联合使用

   (2) 建议以sql原生语句的形式去代码创建表跟数据库

   (3) sqlite3 只支持? 和:啥 这2个占位符格式,一般使用? 作为占位符,  "?",a 这种形式中间以逗号间隔

   (4) sql语句不建议拼装

class sqlit_handle:
    """
    数据库操作
    """
    def __init__(self):
        self.conn = sqlite3.connect('record_price.db')
        self.cursor = self.conn.cursor()
        print("1111")

    def edit_add(self, content, k):
        if k == 0:
            self.cursor.execute('insert into DC_Adaptors values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )',(content[0], content[1], content[2],
                                                                   content[3], content[4], content[5],
                                                                   content[6], content[7], content[8],
                                                                   content[9], content[10], content[11],
                                                                   content[12], content[13], content[14]))
            self.conn.commit()
        else:
            self.cursor.execute('insert into DC_Cables values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                                (content[0], content[1], content[2],
                                 content[3], content[4], content[5],
                                 content[6], content[7], content[8],
                                 content[9], content[10], content[11],
                                 content[12], content[13]))
            self.conn.commit()

    def edit_out_DC(self):
        data_out1 = self.cursor.execute("select * from DC_Adaptors").fetchall()  # 列表里面套元组的形式
        data_out2 = self.cursor.execute("select * from DC_Cables").fetchall()
        return data_out1, data_out2

 

posted @ 2018-12-04 10:01  Corey0606  阅读(1307)  评论(0编辑  收藏  举报