使用python win32com不能在MS Word 2007中创建两个单独的表 [英] Using python win32com can't make two separate tables in MS Word 2007

查看:91
本文介绍了使用python win32com不能在MS Word 2007中创建两个单独的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python在新的Microsoft Word文档中创建多个表.我可以创建第一个表.但是我认为我的COM Range对象配置错误.它不是指向终点.第一个表放在"Hello I a text!"之前,第二个表放在第一个表的第一个单元格内.我认为从wordapp返回范围会返回整个范围,然后使用wdCollapseStart枚举(我认为是1)将其折叠.(我在Python win32com中找不到常量.).因此,将一个表添加到Range的末尾会将其添加到文档的末尾,但这没有发生.

I am trying to create multiple tables in a new Microsoft Word document using Python. I can create the first table okay. But I think I have the COM Range object configured wrong. It is not pointing to the end. The first table is put before "Hello I am a text!", the second table is put inside the first table's first cell. I thought that returning a Range from wordapp will return the full range, then collapse it using wdCollapseStart Enum which I think is 1. (I can't find the constants in Python win32com.). So adding a table to the end of the Range will add it to the end of the document but that is not happening.

有什么想法吗?

感谢蒂姆

import win32com.client

wordapp = win32com.client.Dispatch("Word.Application") 
wordapp.Visible = 1 
worddoc = wordapp.Documents.Add()
worddoc.PageSetup.Orientation = 1 
worddoc.PageSetup.BookFoldPrinting = 1 
worddoc.Content.Font.Size = 11
worddoc.Content.Paragraphs.TabStops.Add (100)
worddoc.Content.Text = "Hello, I am a text!"

location = worddoc.Range()
location.Collapse(1)
location.Paragraphs.Add()
location.Collapse(1)
table = location.Tables.Add (location, 3, 4)
table.ApplyStyleHeadingRows = 1
table.AutoFormat(16)
table.Cell(1,1).Range.InsertAfter("Teacher")

location1 = worddoc.Range()
location1.Paragraphs.Add()
location1.Collapse(1)
table = location1.Tables.Add (location1, 3, 4)
table.ApplyStyleHeadingRows = 1
table.AutoFormat(16)
table.Cell(1,1).Range.InsertAfter("Teacher1")
worddoc.Content.MoveEnd
worddoc.Close() # Close the Word Document (a save-Dialog pops up)
wordapp.Quit() # Close the Word Application

推荐答案

问题似乎出在代表文档一部分的Range对象中.在我的原始代码中,Range对象包含第一个单元格,并从第一个单元格开始,并在该单元格中插入.相反,我想在范围的末尾插入.所以我得到了下面的代码替换工作.在Add()调用之后,我将Collapse移到了其中,并将其参数设为0.现在,每个Range对象只有一个Collapse调用.

The problem seems to be in the Range object that represents a part of the document. In my original code the Range object contains the first cell and starts at the first cell, where it will insert. Instead I want to insert at the end of the range. So I got the following code replacement to work. I moved the Collapse after the Add() call and gave it an argument of 0. Now there is only one Collapse call per Range object.

location = worddoc.Range()
location.Paragraphs.Add()
location.Collapse(0)

现在代码可以正常工作了,我可以从数据库中读取数据,并从每个条目中填充新表.

Now the code works, I can read from a database and populate new tables from each entry.

蒂姆

这篇关于使用python win32com不能在MS Word 2007中创建两个单独的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆