使用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()
相关推荐
M--Y4 分钟前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静35 分钟前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL12342 分钟前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_091 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
databook4 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈5 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao6 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
用户019027581617 小时前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
wuyk5558 小时前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
2601_967979129 小时前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt