首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django和python-docx

Django和python-docx
EN

Stack Overflow用户
提问于 2013-11-26 07:22:13
回答 2查看 2.9K关注 0票数 2

我试图通过python-docx和django创建一个docx文件。

使用python直接运行示例脚本(example-makedocument.py)。一份“工作副本”。它按照预期生成示例docx文件。

然后,我尝试将example-makedocument.py代码移动到Django视图中。这篇文章底部的代码是该视图的代码。你会看到我在前面做了一些小的修改,但总体上没有改变。

在运行此视图时,我会发现无法找到图像文件的错误。

代码语言:javascript
复制
[Errno 2] No such file or directory: 'image1.png'

我有:

  • 确保文件夹/文件结构与工作副本相同(它需要其子文件夹才能正常工作)
  • 我尝试过将docx.py template_dir硬编码到保存文件夹/文件的位置(我检查了这些结果是否指向与工作副本相同的最终路径)。
  • 我已经从示例中删除了图像,但是它导致了错误local variable 'contenttypes' referenced before assignment

我认为这与道路有关,但我不知道为什么/如何?有人能帮忙吗?

完整的python代码可用这里

我的看法是:

代码语言:javascript
复制
from myapp.libs.docx.docx import *
# ** commented out below line, replaced with above **
#from docx import *

def export_docx(request):

# ** commented out below line **
#if __name__ == '__main__':
    # Default set of relationshipships - the minimum components of a document
    relationships = relationshiplist()

    # Make a new document tree - this is the main part of a Word document
    document = newdocument()

    # This xpath location is where most interesting content lives
    body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]

    # Append two headings and a paragraph
    body.append(heading("Welcome to Python's docx module", 1))
    body.append(heading('Make and edit docx in 200 lines of pure Python', 2))
    body.append(paragraph('The module was created when I was looking for a '
        'Python support for MS Word .doc files on PyPI and Stackoverflow. '
        'Unfortunately, the only solutions I could find used:'))

    # Add a numbered list
    points = [ 'COM automation'
             , '.net or Java'
             , 'Automating OpenOffice or MS Office'
             ]
    for point in points:
        body.append(paragraph(point, style='ListNumber'))
    body.append(paragraph('For those of us who prefer something simpler, I '
                          'made docx.'))
    body.append(heading('Making documents', 2))
    body.append(paragraph('The docx module has the following features:'))

    # Add some bullets
    points = ['Paragraphs', 'Bullets', 'Numbered lists',
              'Multiple levels of headings', 'Tables', 'Document Properties']
    for point in points:
        body.append(paragraph(point, style='ListBullet'))

    body.append(paragraph('Tables are just lists of lists, like this:'))
    # Append a table
    tbl_rows = [ ['A1', 'A2', 'A3']
               , ['B1', 'B2', 'B3']
               , ['C1', 'C2', 'C3']
               ]
    body.append(table(tbl_rows))

    body.append(heading('Editing documents', 2))
    body.append(paragraph('Thanks to the awesomeness of the lxml module, '
                          'we can:'))
    points = [ 'Search and replace'
             , 'Extract plain text of document'
             , 'Add and delete items anywhere within the document'
             ]
    for point in points:
        body.append(paragraph(point, style='ListBullet'))

    # Add an image
    relationships, picpara = picture(relationships, 'image1.png',
                                     'This is a test description')
    body.append(picpara)

    # Search and replace
    print 'Searching for something in a paragraph ...',
    if search(body, 'the awesomeness'):
        print 'found it!'
    else:
        print 'nope.'

    print 'Searching for something in a heading ...',
    if search(body, '200 lines'):
        print 'found it!'
    else:
        print 'nope.'

    print 'Replacing ...',
    body = replace(body, 'the awesomeness', 'the goshdarned awesomeness')
    print 'done.'

    # Add a pagebreak
    body.append(pagebreak(type='page', orient='portrait'))

    body.append(heading('Ideas? Questions? Want to contribute?', 2))
    body.append(paragraph('Email <python.docx@librelist.com>'))

    # Create our properties, contenttypes, and other support files
    title    = 'Python docx demo'
    subject  = 'A practical example of making docx from Python'
    creator  = 'Mike MacCana'
    keywords = ['python', 'Office Open XML', 'Word']

    coreprops = coreproperties(title=title, subject=subject, creator=creator,
                               keywords=keywords)
    appprops = appproperties()
    contenttypes = contenttypes()
    websettings = websettings()
    wordrelationships = wordrelationships(relationships)

    # Save our document
    savedocx(document, coreprops, appprops, contenttypes, websettings,
             wordrelationships, 'Welcome to the Python docx module.docx')

========

已更新。下面提供了我找到的解决方案的细节。

docx.py代码假设路径与实际路径不同。这导致image1.png文件“丢失”。完成下面的步骤为我解决了这个问题。

  1. 编辑了docx.py文件并添加了一个变量: docx_dir =‘/path/to/docx/文件夹’
  2. 编辑下面的行(docx.py)以使用上述变量(大约显示行号,将与原始源略有不同)
代码语言:javascript
复制
1. shutil.copyfile(join(docx\_dir, picname), join(media\_dir, picname))
2. pixelwidth, pixelheight = Image.open(join(docx\_dir, picname)).size[0:2]

  1. 以上所述消除了路径问题。但是现在我遇到了错误local variable 'contenttypes' referenced before assignment。我发现这个错误不是通过与路径有关的方法解决的,而是通过重复的名称解决的(我不完全理解为什么仍然如此)。

注意:下面的代码位于我的视图or..if中,与example-makedocument.py中的原始源代码its相比较

在此之前:

代码语言:javascript
复制
contenttypes = contenttypes()
websettings = websettings()
wordrelationships = wordrelationships(relationships)

之后:

代码语言:javascript
复制
contentt = contenttypes()
webs = websettings()
wordr = wordrelationships(relationships)

# Save our document
savedocx(document, coreprops, appprops, contentt, webs,
         wordr, 'Welcome to the Python docx module.docx')
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-26 07:40:25

image1.png必须位于正在运行的Python程序的当前目录中,或者作为相对于正在运行的程序的当前目录的路径提供,或者更少的可移植性,但可能更容易工作,但它可以作为绝对路径提供。

特别是,我认为您可能会发现在这篇文章中给出的答案最有帮助:使用WSGI和Apache运行Python的工作目录 (用于动态地确定image.png的绝对路径)。

票数 2
EN

Stack Overflow用户

发布于 2014-06-09 14:29:51

自上面编写的代码以来,python模块发生了一些变化。现在,在django中添加一个图像如下所示:

代码语言:javascript
复制
from docx import *
from docx.shared import Inches
document = Document()
document.add_picture((r'%s/static/images/my-header.png' % (settings.PROJECT_PATH)), width=Inches(4))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20210833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档