尝试从数据库检索图像到 python docx 时出现属性错误
Attribute Error on trying to retrieve image to python docx from Database
我正在尝试使用 python docx 将数据库中存储的文本和图像存储到 word 文档中,文本检索正常,但在尝试检索图像时出现以下错误。 AttributeError:'bytes' 对象没有属性 'seek'。代码如下。
import sqlite3
from docx import Document
document = Document()
name = "The heading of the report"
document.add_heading(name,0)
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users where UserID = 1")
images in binary format
data = cursor.fetchall()
for row in data:
zero = row[0]
one = row[1]
two = row[2]
document.add_paragraph(str(zero))
document.add_paragraph(str(one))
document.add_picture(two)
document.save('UserReport.docx')
connection.close()
为了便于测试,dBTable结构如下:
CREATE TABLE Users (
UserID integer,
UserName text NOT NULL,
UserImage Blob,
PRIMARY KEY(`UserID`)
);
我可以看到错误是由于这一行而产生的,document.add_picture(二)。但不明白原因,将不胜感激您的意见。
.add_picture()
的 picture
参数需要是类文件对象。试试这个方法:
from StringIO import StringIO # would be from io import BytesIO in Python3
image_stream = StringIO(two)
document.add_picture(image_stream)
我正在尝试使用 python docx 将数据库中存储的文本和图像存储到 word 文档中,文本检索正常,但在尝试检索图像时出现以下错误。 AttributeError:'bytes' 对象没有属性 'seek'。代码如下。
import sqlite3
from docx import Document
document = Document()
name = "The heading of the report"
document.add_heading(name,0)
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users where UserID = 1")
images in binary format
data = cursor.fetchall()
for row in data:
zero = row[0]
one = row[1]
two = row[2]
document.add_paragraph(str(zero))
document.add_paragraph(str(one))
document.add_picture(two)
document.save('UserReport.docx')
connection.close()
为了便于测试,dBTable结构如下:
CREATE TABLE Users (
UserID integer,
UserName text NOT NULL,
UserImage Blob,
PRIMARY KEY(`UserID`)
);
我可以看到错误是由于这一行而产生的,document.add_picture(二)。但不明白原因,将不胜感激您的意见。
.add_picture()
的 picture
参数需要是类文件对象。试试这个方法:
from StringIO import StringIO # would be from io import BytesIO in Python3
image_stream = StringIO(two)
document.add_picture(image_stream)