pythondocx 使用教程

2025-09-26 00:50:27

1、在编辑器里面输入import docx,并且运行一下。

如果没有问题就继续,有问题就代表没有安装库。

那么需要在终端窗口pip install python-docx进行安装。

pythondocx 使用教程

2、这里创建一个docx文档作为示范。

doc = docx.Document("abc.docx")

print(len(doc.paragraphs))

len(doc.paragraphs)可以查看一共有多少行。

pythondocx 使用教程

pythondocx 使用教程

3、print(doc.paragraphs[0].text)

print(doc.paragraphs[1].text)

paragraphs是列表的形式,所以要以这个方式来调用,记得加text。

pythondocx 使用教程

4、for p in doc.paragraphs:

    print(p.text)

如果我们要把内容全部输入,可以用for循环来进行操作。

pythondocx 使用教程

5、doc = docx.Document()

doc.add_paragraph("This is a test file.")

doc.save("testfile.docx")

我们还可以新生成一个文档,并且进行保存。

add_paragraph是加语句。

pythondocx 使用教程

pythondocx 使用教程

6、doc = docx.Document()

doc.add_heading("The title", 0)

doc.add_paragraph("This is the sentece.")

doc.save("testfile.docx")

如果文档已经存在,那么这样会直接覆盖内容,add_heading可以加标题,第二个参数可以设置级别。

pythondocx 使用教程

pythondocx 使用教程

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢