Я пытаюсь обновить таблицу microsoft word - 2010, удалив ее содержимое (кроме первого содержимого строки) с помощью клиентского компонента python и win32com. Я даже посмотрел на библиотеку MSDN (http://msdn.microsoft.com/en-us/library/bb244515.aspx) и обнаружил, что Delete может помочь мне в этом, что-то вроде этого. (не также имел взгляд @How to read contents of an Table in MS-Word file Using Python?)Python - невозможно редактировать содержимое таблицы в Microsoft Word с помощью win32com
..///
# delete row 1 of table 1
doc.Tables(1).Rows(1).Delete
# delete cell 1,1 of table 1
doc.Tables(1).Cell(1, 1).Delete
..///
но делать эти шаги, строка таблицы не удаляются (ни ячейка [1,1] удаляется). Есть что-то, что мне не хватает? Любые предложения приветствуются.
функция Python для очистки содержимого таблицы наклеен здесь со
..//
def updateTable(name):
#tell word to open the document
word.Documents.Open (IP_Directory_Dest + "\\" + name)
#open it internally (i guess...)
doc = word.Documents(1)
## doc.Content.Text = "This is the string to add to the document."
## doc.Content.MoveEnd()
## doc.Content.Select
## doc.Tables(1).Rows(2).Select
## Selection.InsertRowsBelow
## doc.Tables [1]. Rows [1]. Cells [1]. Range.Text = '123123 '
## doc.Tables [1]. Rows.Add() # add a line
# specifically select TABLE # 1
table = doc.Tables(1)
# count the number of rows in TABLE # 1
numRows = table.Rows.Count
# count number of columns
numCols = table.Columns.Count
print ('Number of Rows in TABLE',numRows)
print ('Number of Columns in TABLE',numCols)
# print the row 1 of TABLE # 1 -- for checking
print ('### 1 - CHECK this ONE ... ',table.Rows(1).Range.Text)
# delete row 1 of table 1
doc.Tables(1).Rows(1).Delete
# delete cell 1,1 of table 1
doc.Tables(1).Cell(1, 1).Delete
# again count the number of rows in table
numRows = table.Rows.Count
print numRows
# print the row 1 of TABLE # 1 -- after Deleting the first ROW --> for checking
print ('### 2 - CHECK this ONE ... ',table.Rows(1).Range.Text)
# get the number of tables
numberTables = doc.Tables.Count
# count the number of tables in document
print numberTables
#delete ALL tables
tables = doc.Tables
for table in tables:
# to get the content of Row # 1, Column # 1 of table
print table.Cell(Row =1, Column = 1).Range.Text
## table.Delete(Row =2)
# this one deletes the whole table (which is not needed)
#table.Delete()
#re-save in IP folder
doc.SaveAs(IP_Directory_Dest + "\\" + name)
#close the stream
doc.Close()
... ///
игнорируйте закомментированные секции (я был пытаясь сделать работу)
спасибо Дэвид. Это действительно помогло удалить строку 1 таблицы 1. Однако любое предложение о том, как очистить содержимое таблицы (сохраняя формат таблицы как есть), а не удалять строку как таковую. Благодарю. – Varun
@Varun: Что происходит, когда вы удаляете эту строку и просто выполняете строку 'doc.Tables (1) .Cell (1, 1) .Delete()'? –
Дэвид, он удаляет только ячейку (1,1) таблицы 1. – Varun