使用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()
相关推荐
2301_795099747 小时前
HTML怎么创建时间轴布局_HTML结构化时间线写法【方法】
jvm·数据库·python
运气好好的7 小时前
CSS组件库如何快速扩展_通过Sass @extend继承基础布局
jvm·数据库·python
m0_613856297 小时前
Go install 命令失效原因解析与正确使用指南
jvm·数据库·python
jaycyj7 小时前
pytest
开发语言·python
Gary Studio7 小时前
安卓HAL编译流程
开发语言·python
tangweiguo030519877 小时前
LangChain + RAG + Agent + 多模态 完整实战教程
python·langchain
我是无敌小恐龙7 小时前
Java SE 零基础入门Day06 方法重载+Debug调试+String字符串全套API详解(超全干货)
java·开发语言·人工智能·python·transformer·无人机·量子计算
aidesignplus7 小时前
从平方到线性:Mamba如何挑战Transformer的长序列效率瓶颈?
人工智能·python·深度学习·vim·transformer
2301_773553627 小时前
Redis怎样优化复制缓冲池大小_调大repl-backlog-size减少频繁的全量同步触发
jvm·数据库·python
三维频道7 小时前
工业级三维扫描实测:汽车灯具复杂结构件的全尺寸 3D 测量方案分析
java·人工智能·python·数码相机·3d·汽车·汽车轻量化制造