使用Python+docx+sqlite3将Word表格内容写入sqlite表中

一、使用Python+docx+sqlite3将Word表格内容写入sqlite表中

python 复制代码
# 导入所需的库
import docx
import sqlite3
import random
import os


# 创建一个空白的word文档对象
doc = docx.Document()

# 在文档中插入一个表格,行数为5+1(表头),列数为3
table = doc.add_table(rows=6, cols=3)
table.style = "Table Grid"

# 获取表格的第一行,即表头,并设置单元格的文本内容
header = table.rows[0].cells
header[0].text = '产品名'
header[1].text = '厂商'
header[2].text = '价格'

# 定义一些随机生成数据的函数
def random_product():

    # 随机返回一个产品名,可以根据需要修改或扩充
    products = ['手机', '电脑', '平板', '耳机', '键盘', '鼠标', '显示器', '路由器', '充电器', '音箱']

    return random.choice(products)

def random_vendor():

    # 随机返回一个厂商名,可以根据需要修改或扩充
    vendors = ['苹果', '华为', '小米', '联想', '戴尔', '惠普', '索尼', '三星', '罗技', '飞利浦']

    return random.choice(vendors)

def random_price():

    # 随机返回一个价格,单位为元,保留两位小数
    return round(random.uniform(100, 10000), 2)

# 遍历表格的剩余行,即表的内容,并填充随机生成的数据
for row in table.rows[1:]:

    cells = row.cells
    cells[0].text = random_product()
    cells[1].text = random_vendor()
    cells[2].text = str(random_price())


# 保存word文档为data.docx
doc.save('data.docx')

# 打开data.docx文档,并获取第一个表格对象
doc = docx.Document('data.docx')
table = doc.tables[0]

if os.path.exists('data.db'):

    # 删除文件
    os.remove('data.db')

# 创建一个sqlite数据库data.db,并获取游标对象
conn = sqlite3.connect('data.db')
cur = conn.cursor()

# 在数据库中创建一个products表,字段与word中的表头相同,价格字段为小数类型,其他为字符串类型
cur.execute('''
CREATE TABLE products (
    产品名 TEXT,
    厂商 TEXT,
    价格 REAL
)
''')

# 遍历word表格的内容行,将每一行的数据插入到products表中
for row in table.rows[1:]:

    cells = row.cells
    product = cells[0].text
    vendor = cells[1].text
    price = float(cells[2].text)
    cur.execute('''
    INSERT INTO products (产品名, 厂商, 价格)
    VALUES (?, ?, ?)
    ''', (product, vendor, price))

# 提交数据库操作,并关闭连接
conn.commit()
conn.close()
相关推荐
爱技术的小伙子16 分钟前
【30天玩转python】面向对象编程基础
开发语言·python
theoxiong27 分钟前
Python的Scapy库详解
开发语言·python·网络协议·tcp/ip·http·信息与通信·scapy
hsg771 小时前
ArcGIS Pro 克隆clone python环境报错问题处理方法
开发语言·python·arcgis
Flying_Fish_roe1 小时前
Reactive 编程-Vert.x
开发语言·python
四代机您发多少1 小时前
入门pytorch
人工智能·pytorch·python
Rin__________2 小时前
Python计算机视觉 第8章-图像内容分类
python·计算机视觉·分类
西猫雷婶2 小时前
python画图|3D直方图基础教程
开发语言·python
守望↪星空2 小时前
画图方法总结
python
码农超哥同学2 小时前
Python知识点:如何使用Python进行Excel文件操作(OpenPyXL、Pandas)
python·面试·excel·pandas·编程
一只会敲代码的小灰灰2 小时前
python学习第九节:爬虫实战-抓取地址库
爬虫·python·学习