使用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()
相关推荐
小鸡吃米…21 小时前
TensorFlow 实现多层感知机学习
人工智能·python·tensorflow
WW、forever21 小时前
【服务器】上传服务器中数据至 FigShare(Python)
运维·服务器·python
2301_8169978821 小时前
Word版本介绍与选择
c#·word·xhtml
宝贝儿好21 小时前
【强化学习】第十章:随机高斯策略
人工智能·python·深度学习·神经网络·机器人·自动驾驶
haosend21 小时前
【练习版】使用paramiko批量的查询,管理,配置路由器交换机
python·路由器·交换机·网络自动化
Dxy12393102161 天前
Python生成随机手机号码
开发语言·python
小帅学编程1 天前
Python学习
开发语言·python·学习
两万五千个小时1 天前
构建mini Claude Code:08 - Fire and Forget:用后台线程解锁 Multi-Agent 并行执行
人工智能·python·架构
JaydenAI1 天前
[拆解LangChain执行引擎]支持自然语言查询的长期存储
python·langchain
dreams_dream1 天前
Python 的 GIL 是什么?有什么影响?
开发语言·python