python对word文档表格的处理

技术QQ交流群:294088839

import docx
import pymysql
#host='localhost',user="root",password='123456',database='datarepair',port=3306,charset='utf8'
con = pymysql.connect(host='127.0.0.1', user="root", password='root', port=3306, charset='utf8')
# print(con)
# 创建游标 连接上后 要先创建这个东西
cur = con.cursor()
# print(cur)
# 连接库
con.select_db('ceshi')
file = docx.Document('tiku/5.docx')
print("段落数:"+str(len(file.paragraphs)))
tables = file.tables
num = len(tables)
for i in range(0, num):
    table = tables[i]
    for i in range(2,len(table.rows)): #从表格第二行开始循环读取表格数据
        # 类型
        result_1 = table.cell(i, 0).text
        # 题型
        result_2 = table.cell(i, 1).text
        # 描述
        result_3 = table.cell(i,2).text
        # 备选一
        result_4 = table.cell(i,3).text
        if result_4 == '':
            result_4 = '无'
        # 备选二
        result_5 = table.cell(i, 4).text
        if result_5 == '':
            result_5 = '无'
        # 备选三
        result_6 = table.cell(i, 5).text
        if result_6 == '':
            result_6 = '无'
        # 备选四
        result_7 = table.cell(i, 6).text
        if result_7 == '':
            result_7 = '无'
        # 备选五
        result_8 = table.cell(i, 7).text
        if result_8 == '':
            result_8 = '无'
        # 答案
        result_9 = table.cell(i, 8).text
        #cell(i,0)表示第(i+1)行第1列数据,以此类推
        # print(result)
        # print(result_1)
        sql = "insert into tiku(type_1,tixing,miaoshu,daan,beixuan1,beixuan2,beixuan3,beixuan4,beixuan5) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
        # 传入元组的形式
        cur.execute(sql, (result_1,result_2,result_3,result_9, result_4, result_5, result_6, result_7, result_8))
        cur.connection.commit()

猜你喜欢

转载自blog.csdn.net/Drug_/article/details/81782003