我正在按照python-docx网站上提供的教程创建一个MS-Word文档但是我收到一个错误:
M:\Sites>python word.py
C:\Program Files\IBM\SPSS\Statistics\22\Python\lib\site-packages\docx\styles\sty
les.py:54: UserWarning: style lookup by style_id is deprecated. Use style name a
s key instead.
warn(msg, UserWarning)
Run Code Online (Sandbox Code Playgroud)
word.py
from docx import Document
from docx.shared import Inches
import json
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', …Run Code Online (Sandbox Code Playgroud) 当我使用 python-docx 创建新文档并添加段落时,它从第一行开始。但是,如果我使用空文档(由于用户定义的样式,我需要它)并添加段落,则文档将始终以空行开头。有什么解决方法吗?
我正在尝试从docx文件中提取页面和标题数据.该文件是几百页,每个页面都有一个表和一个标题.标题具有需要与每个表配对的相关信息.我能够提取标题和表格数据,我无法将它们可靠地配对在一起.
使用win32com这是我到目前为止所拥有的
# getting the table page number
app = Dispatch("Word.Application")
doc = app.Documents.Open(filename)
table_1_page = doc.Tables(1).Range.Information(3) # 3 == wdActiveEndPageNumber
Run Code Online (Sandbox Code Playgroud)
出现此问题的原因是标题TextFrames并且在多个页面上重复,因此当我调用时:
# getting the header page number
doc.Sections(1).Headers(1).Shapes(1).TextFrame.TextRange.Information(3)
Run Code Online (Sandbox Code Playgroud)
我得到了TextFrame发生的其中一个页面.页面选择似乎有点武断,有时它的第一个是最后一个,但它不可预测.
我花了一点时间阅读了对象模型在这里.最终,捕捉每页显示的所有项目而不重新发明轮子会很好.
# filename docx_parser.py
import pythoncom
class OpenDoc(object):
def __init__(self, docx_path):
import win32com.client as win32
self.path = docx_path
self.word = win32.Dispatch("Word.Application")
self.word.Visible = 0
self.word.Documents.Open(p)
self.doc = self.word.ActiveDocument
def get_table_count(self):
return self.doc.Tables.Count
def count_table_rows(self, table):
return table.Rows.Count
def count_table_columns(self, table):
return table.Columns.Count
def get_headers(self):
headers = self.doc.Sections(1).Headers(1) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 docx-python 库在文档中间添加分页符。
似乎在添加分页符时,分页符被添加到文档的末尾。有没有一种方法可以将分页符添加到特定位置?
这是我目前的代码。
from docx import Document
from docx.shared import Inches
demo='gm.docx'
document = Document(docx=demo)
for paragraph in document.paragraphs:
if 'PUB' in paragraph.text:
document.add_page_break()
document.save('gm.docx')
Run Code Online (Sandbox Code Playgroud) 我必须从 CSV 文件中添加一个大约 1500 行和 9 列(75 页)的表格到 docx word 文档中。使用 python-docx。
我尝试了不同的方法,用 pandas 读取 csv 或直接打开 de csv 文件,我花了大约 150 分钟按照我选择的方式独立完成工作
我的问题是这是否是正常行为,或者是否存在任何其他方法来改进这项任务。
我使用这个 for 循环来读取几个 cvs 文件并以表格式解析它
for toTAB in listBRUTO:
df= pd.read_csv(toTAB)
# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = doc.add_table(df.shape[0]+1, df.shape[1])
t.style = 'LightShading-Accent1' # border
# add the header rows.
for j in range(df.shape[-1]):
t.cell(0,j).text = df.columns[j]
# add …Run Code Online (Sandbox Code Playgroud) 我使用 python-docx 中的示例,运行代码后我找不到 docx 文件在哪里,我可以指出我想要添加的特定路径吗?
from docx import Document
from docx.shared import Inches
document = Document('C:\Users\Administrator\Desktop\python test\update_test\\test.docx')
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)
filename='test.docx'
filepath=r'C:\Users\Administrator\Desktop\python test\update_test'+filename
document.add_page_break()
document.save(filepath)
Run Code Online (Sandbox Code Playgroud) 我在更新由 Linux 上的python-docx生成的 docx 文件中的目录时遇到问题。一般来说,创建TOC并不难(感谢这个答案/sf/answers/3403559211/和这个线程https://github.com/python-openxml/python-docx/issues/36)
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
paragraph = self.document.add_paragraph()
run = paragraph.add_run()
fldChar = OxmlElement('w:fldChar') # creates a new element
fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:t')
fldChar3.text = "Right-click …Run Code Online (Sandbox Code Playgroud) 我正在尝试安装docx包。但得到以下信息ImportError:
ImportError: cannot import name Document
因此,按照此处的建议,我尝试了:
pip install python-docx
但出现以下错误(python版本:2.7.15)
..
..
..
creating build/lib/docx/templates
copying docx/templates/default-header.xml -> build/lib/docx/templates
copying docx/templates/default-settings.xml -> build/lib/docx/templates
copying docx/templates/default-footer.xml -> build/lib/docx/templates
error: can't copy 'docx/templates/default-docx-template': doesn't exist or not a regular file
Command
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import
setuptools,tokenize;__file__='/private/var/folders/0c/v_yb4q7n2h3fg94rlfrr165r0000gn/T/pip-build-ks26RP/python-docx/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n',
'\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/0c/v_yb4q7n2h3fg94rlfrr165r0000gn/T/pip-1SQvtb-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/0c/v_yb4q7n2h3fg94rlfrr165r0000gn/T/pip-build-ks26RP/python-docx/
Run Code Online (Sandbox Code Playgroud) 我执行以下操作:
from docx import Document
document = Document('text.docx')
document.paragraphs[42].text
Run Code Online (Sandbox Code Playgroud)
它给出了 ''我输入的任何数字,并且 for 循环查找和替换单词不起作用。但是如果我用 保存文档document.save('text2.docx'),则该文档不为空。
该文档相对较大,包含许多不同的格式、图像、表格、样式。
我的任务是查找并替换 docx 文档中的单词,并对以下单词进行一些更正,所以如果您建议使用其他工具,我会很高兴
python-docx ×10
python ×8
python-2.7 ×3
ms-word ×2
docx ×1
importerror ×1
macos ×1
openxml ×1
python-3.x ×1
split ×1
win32com ×1