使用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()
相关推荐
两万五千个小时2 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿5 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户83562907805119 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng821 小时前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi21 小时前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee21 小时前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python
闲云一鹤1 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
Rockbean1 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
曲幽1 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi