How do you iterate through a table and edit information with pptx in python? - python-3.x

How do you iterate through a table and find and replace text? I'm able to go through text boxes as below but need to be able to access and edit information in a table:
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
j = 0
k = 0
for i in searchList:
#find the search term from the searchList
searchString = searchList[j]
j+=1
#replace the search term from the dataframe
dfIndexName = dfIndex.keys()[k]
k+=1
replaceString = df.at[0, dfIndexName]
if (shape.text.find(searchString))!=1:
text_frame = shape.text_frame
cur_text = text_frame.paragraphs[0].runs[0].text
new_text = cur_text.replace(searchString, str(replaceString))
text_frame.paragraphs[0].runs[0].text = new_text
Thanks!

I'm not sure what you want to do with searchList, but this is how you can access cells in a table.
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_table:
table = shape.table
for cell in table.iter_cells():
# here you can access the text in cell by using
# cell.text
# just remember that the shape object refers to the table in this context not the cell

Related

Changing Value of Combo Box to another Value in VB

I am trying to change the value of a combo box value "Black Shredded - 7.90" to just show "Black Shredded" when it is selected
Dim intIndex As Integer
Dim strString1 As String
Dim strString2 As String
strString1 = cboProduct.SelectedItem
intIndex = strString1.IndexOf(" ")
strString2 = strString1.Remove(intIndex + 9)
If cboProduct.SelectedIndex = 0 Then
cboProduct.Text = strString2
End If
I went through the values and they show as they should but it isn't changing the combobox value what could I be doing wrong?
If you have just added Strings to the ComboBox in the first place then you need to replace the existing item with the new value. This:
cboProduct.Text = strString2
should be this:
cboProduct.Items(cboProduct.SelectedIndex) = strString2
You can just use 0 rather than cboProduct.SelectedIndex, given that you have already confirmed that that is the index at that point.
Setting the Text property doesn't affect the items at all. If DropDownStyle is set to DropDown then the specified text will be displayed but no item will be selected. If DropDownStyle is set to DropDownList then the item with that text will be selected, if one exists. Either way, no item is added or changed.

Roman numeral page numbers for table of contents

I'm generating word docs entirely in VBA and am aiming to have roman numeral page numbers for my table of contents and numeric page numbers for the remainder of the document. My table of contents spans multiple pages and is variable in page size.
How would I achieve roman numeral page numbers for only a table of contents of variable page span?
Any help would be greatly appreciated.
If you don't know where to start, try this approach in Word:
Insert a section break after the table of content pages.
Turn on the macro recorder
Format the page numbers in the first section with Roman numerals
select the next section and unlink it from the previous section
Format the page numbers in the second section with regular numbers
Turn off the macro recorder.
Adjust the code as required.
I also find Word fiddly in this area, so here's some code to show one possible example. The code clears the content of the current document (so don't run it in your existing document!!), then generates a few headings, followed by a table of contents, both of which are then split by a section break. The section break allows different formatting of the page number (roman numerals for the first section, and arabic for the second). Change the for loop up to 100 will demonstrate multiple ToC pages. Might point you in the right direction. Cheers.
Option Explicit
Public Sub PageNumbers()
Dim myRange As Range
Dim Counter As Long
Dim myTOC As TableOfContents
' Delete word document content
ActiveDocument.StoryRanges(wdMainTextStory).Delete
' Add in some headings for testing
Set myRange = ActiveDocument.Range(0, 0)
For Counter = 1 To 10
myRange.InsertAfter "Heading " & Counter
myRange.Style = WdBuiltinStyle.wdStyleHeading1
myRange.InsertParagraphAfter
Next
' Add in a page number
With ActiveDocument.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.Add _
PageNumberAlignment:=wdAlignPageNumberLeft, _
FirstPage:=True
End With
' Add in a section break at the start of the document
Set myRange = ActiveDocument.Range(0, 0)
myRange.InsertBreak Type:=wdSectionBreakNextPage
myRange.InsertParagraphAfter
' Insert a table of contents (into the first section)
Set myRange = ActiveDocument.Range(0, 0)
Set myTOC = ActiveDocument.TablesOfContents.Add(myRange, True, 1, 3, False)
' Format the page number of the first section to have roman numerals
With ActiveDocument.Sections.Item(1).Footers.Item(1).PageNumbers
.NumberStyle = wdPageNumberStyleLowercaseRoman
.HeadingLevelForChapter = 0
.IncludeChapterNumber = False
.ChapterPageSeparator = wdSeparatorHyphen
.RestartNumberingAtSection = False
.StartingNumber = 0
End With
' Format the page number of the second section to have arabic numerals
With ActiveDocument.Sections.Item(2).Footers.Item(1).PageNumbers
.NumberStyle = wdPageNumberStyleArabic
.HeadingLevelForChapter = 0
.IncludeChapterNumber = False
.ChapterPageSeparator = wdSeparatorHyphen
.RestartNumberingAtSection = True
.StartingNumber = 1
End With
End Sub
The Output:

How can I stop python-docx from inserting a carriage return before my cell text

I want a paragraph inside a cell, but I get a stray carriage return which pushes down the text by one line:
My code:
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm
document = Document()
document.add_heading("The Heading", 1).alignment = WD_ALIGN_PARAGRAPH.CENTER
table = document.add_table(rows=0, cols=2)
table.style = 'Table Grid'
for i in range(3):
row_cells = table.add_row().cells
row_cells[0].text = 'row {}, col 1'.format(i)
row_cells[0].width = Cm(3)
row_cells[1].width = Cm(8)
p = row_cells[1].add_paragraph()
p.add_run('This is an example of')
p.add_run(' some text').bold = True
p.add_run(' in a table cell.')
document.save('test.docx')
How can I get the cell text to align at the top of the cell without the stray CR? And how should I be setting the cell widths to 3 cm and 8 cm: setting _Cell.width isn't respected.
I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:
p = row_cells[1].paragraphs[0]
p.add_run('This is an example of')
p.add_run(' some text').bold = True
p.add_run(' in a table cell.')
To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):
table.columns[0].width = Cm(3)
table.columns[1].width = Cm(8)
Tanks for the clear_content it made my image not to be placed beneath a linefeed, tanks for the coment, it was the last pice of advice I needed after hours of problemsolving:
#This seams to clear the content in my cell
tables[1].rows[0].cells[4]._element.clear_content()
#Then when the image is inserted to the cell it is not placed one linefeed down.
img = tables[1].rows[0].cells[4].add_paragraph().add_run().add_picture('AgressoLogga.png', width=Inches(0.4))

openpyxl - read data validation - list

I have an excel sheet, with data validation property - list.
I need to make a dictionary of column_name and associated drop down list values.
For e.g: {A:[a1, a2, a3], B:[b1, b2], C:[c1, c2, c3, c4]}.
There are multiple examples of how to embed data validation list in the excel,
But how do I read it?
I have tried the simple code:
from openpyxl import load_workbook
excel = load_workbook('test.xlsx')
sheet = excel.get_sheet_by_name('RequiredFormat')
for row in sheet.iter_rows():
for cell in row:
print(cell.value)
input("Proceed ?")
And I checked for the options available for the cell.
But there is nothing that says data validation or lists.
Is there a way?
You can not read existing data validation currently. Read Openpyxl documentation
As #Jeanne Lane points out in a comment, there is some ability to read data validation:
https://foss.heptapod.net/openpyxl/openpyxl/-/issues/827#note_124765
for dv in worksheet.data_validations.dataValidation:
# dv.type has the type, and other things here....
here is a snapshot of code I'm about to use to read the list values and for which cell
tstlst = ws.data_validations.dataValidation
print('---')
print(tstlst)
print('---')
nr = 0
for tst2 in tstlst:
nr += 1
print(str(nr) + " : " + str(tst2))
tst3 = tst2.sqref
print('sqref: ' + str(tst3))
tst4 = tst2.formula1
print('list: ' + tst4)
maybee this is helpfull
This produces following output for a datavalidation list I have in A13
2 : <openpyxl.worksheet.datavalidation.DataValidation object>
Parameters:
sqref=<MultiCellRange [A13]>, showErrorMessage=True, showDropDown=None, showInputMessage=True, allowBlank=False, errorTitle=None, error=None, promptTitle=None, prompt=None, type='list', errorStyle=None, imeMode=None, operator=None, formula1='"val1,val2,val3"', formula2=None
sqref: A13
list: "val1,val2,val3"

Load image to a label in userform using vba

I am working on a userform to load Images over labels, I am getting a
Run time error '75': Path/File access error
with below code,
dim solArr as variant
solArr = Split("1.jpg,2.jpg,3.jpg",",")
For i = LBound(solArr) To UBound(solArr)
'For rating image
Dim ratingImageName As String
ratingImageName = "D:\somepath" & "\" & solArr(i)
Set imageStar = UserForm1.Frame3.Controls.Add("Forms.Label.1")
imageStar.Top = 40 + (i * 50)
imageStar.Left = 420
imageStar.Height = 20
imageStar.Width = 100
imageStar.Picture = LoadPicture(ratingImageName)
Next
But, if i use ratingImageName as "D:\Somepath\1.jpg" no error is recieved...
Is there a better way to do it?
Hmmm.. solArr = Array("1.jpg","2.jpg","3.jpg")
I was picking up a value from cell as
1.jpg
2.jpg
3.jpg
the sentence replace(arrSol(i),chr(10),"") solved the problem.
Set imageStar = UserForm1.Frame3.Controls.Add("Forms.Label.1")
I have an array of many items in-game. Example item1, item2, item3... How to change index at item (Exemple item & i) and add a picture it item in label in Form.

Resources