I have searched high and low (on various forums) and simply can't find the answer. I have a table in a docx file and would like to use the docx Python module to modify it.
I need to add a column to the left side of the table. According to the documentation, using the add_column() function adds a column to the right side of the table.
I have also tried changing the directionality of the table to a RTL table with the following code:
import docx
from docx.enum.table import WD_TABLE_DIRECTION
file = test.docx
doc = docx.Document(file)
tbls = doc.tables #this gives me 3 tables in a list of table objects
test = tbls[1]
test.table_direction = WD_TABLE_DIRECTION.RTL
test.add_column(1)
doc.save(file)
Upon opening the resulting file, I found that the code still adds a column only to the left side.
Does someone know how to add a column to the right side of a table?
Many thanks in advance!
You can try LTR, and also use Inches to define the column width so that the added column can be displayed correctly.
import docx
from docx.enum.table import WD_TABLE_DIRECTION
from docx.shared import Cm, Inches
file = 'test.docx'
doc = docx.Document(file)
tbls = doc.tables
test = tbls[1]
test.table_direction = WD_TABLE_DIRECTION.LTR
test.add_column(Inches(1.0))
doc.save(file)
Related
i need to print an excel sheet and need to do it using some kind of python script. So far i have used win32com in my script and i also got it done to get a printout using the following code:
import win32com.client
o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
wb = o.Workbooks.Open(r'C:\test.xlsx')
ws = wb.Worksheets[1]
ws.PrintOut()
Unfortunately before i actually print the excel-sheet i need to adjust the print settings of this sheet/file: change format to landscape and change to small/narrow margin.
I have found this site that might contain just what i need:
https://msdn.microsoft.com/en-us/library/aa220363(v=office.11).aspx
Unfortunately so far i have not been able to change the desired print properties. I hope someone can help me with this or at least get me headed into the right direction.
You can edit the print settings using the PageSetup Method (https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa173425%28v%3doffice.11%29). Does not seem to have a narrow/wide/normal margin setting as you normally see in the excel application, but you can specify the margins yourself.
ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesTall = 1
ws.PageSetup.FitToPagesWide = 1
ws.PageSetup.PrintArea = print_area
ws.PageSetup.LeftMargin = 25
ws.PageSetup.RightMargin = 25
ws.PageSetup.TopMargin = 50
ws.PageSetup.BottomMargin = 50
wb.ExportAsFixedFormat(0, path_to_pdf)
I am using ExportAsFixedFormat, but I guess this should work for PrintOut() too.
Reference: Print chosen worksheets in excel files to pdf in python
EDIT:
The FitToPagesTall (fits all rows on one page) and FitToPagesWide (fits all columns on one page) settings will mess up your eventual print area if you have them both set to True. You will need to specify at least one of them as False to see your margin settings take effect.
ws.PageSetup.FitToPagesTall = False
ws.PageSetup.FitToPagesWide = 1
I am working in python with ArcMap & had a question. Is there a way to import the data from an attribute table into python, and if you can how do you select which attributes to print?
Thank You
A clean looking way of presenting an attribute table in python can be executed through a pandas dataframe...especially if you are working with shapefiles. The input must be a dbf file.
# Pandas Option, python 2.7
import arcpy, os, pandas
inTable = r'.dbf'
os.chdir(os.path.dirname(inTable))
outTable = 'table.xls'
arcpy.TableToExcel_conversion(inTable, outTable)
df = pandas.read_excel(outTable)
df.head() # Shows first five records of attribute table
Using SearchCursors and UpdateCursors is also an option if you want to update fields and work directly with the shapefile.
# SearchCursor option, python 2.7
import arcpy, os
shapefile = r'.shp'
cursor = arcpy.da.SearchCursor(shapefile, '*')
attributes = []
for row in cursor:
attributes.append(row)
If you want to find a specific record by a certain field name...for example ID 50...
for record in attributes:
if record[0] == 50:
print record
I'm trying to do some work on a complex Excel Workbook which has a large number of variables which have been created and used using the Name Box feature. See picture attached for example/detail.
I'd like to store or change DeathRate or maybe read all the Name Boxes and create a dictionary between names and locations of the cell from outside Excel.
I'm using the win32com library in Python but I guess I could switch to another Excel reader as long as it copes with XLSX files.
Has someone come across this before?
Found the solution, see code below:
import os
from win32com.client import Dispatch #win32com is based around cells beginning at one.
app_xl = Dispatch("Excel.Application")
WORKING_DIR = os.getcwd()
excelPath = WORKING_DIR + "\SampleModel.xls"
wb = app_xl.Workbooks.Open(excelPath)
# Get Named Boxes
name_box_list = [x for x in app_xl.ActiveWorkbook.Names]
name_box_map = {x.Name:x.Value for x in name_box_list}
print name_box_list
print name_box_map
# Change Named Boxes
name_box_list[0].Name = u'NewName'
name_box_list[0].Value = u'=model!$B$5'
name_box_map = {x.Name:x.Value for x in name_box_list}
I tried to build a table of contents in Reportlab (but failed ... and did not insisted too much as and seems even more than what I'm needing .. might be I'll give a try newly in the future ..).
As now I'd be quite happy to have some simple text as guide for a document (the document is mainly composed by some Pandas generated numbered grids. Id' simly like to have a text with the titles of the grids at the beginning of the Reportlab generated .pdf).
My goal looked so very simple and was to append two Platypuses one with the titels and one with the grids but did not worked. So I move to an even simpler goal and tried to append two Platypuses plain texts .. but that did not worked again ... :-(
My code as below:
# settings
from reportlab.pdfgen import canvas
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import *
styles = getSampleStyleSheet()
PATH_OUT = "C:\\"
titolo = 'Test.pdf'
doc = SimpleDocTemplate( PATH_OUT + titolo )
elements0 = []
elements1 = []
elements2 = []
# 1-st platypus
elements0.append(Paragraph("The Platypus0", styles['Heading1']))
elements0.append(Paragraph("Very <i>Special</i>!", styles['Normal']))
# 2-nd platypus
elements1.append(Paragraph("The Platypus1", styles['Heading1']))
elements1.append(Paragraph("Very <i>Special</i>!", styles['Normal']))
# append them
elements2 = elements0.append(elements1)
# Write the document
doc.build(elements2)
The issue I have is this is miserably crashing apparently because of no len() resulting object.
Do you have any suggestion that might be of help in this ? If I use elements0 or elements1, one separate from the other, they work pretty smoothly but when I try to append one with the other it does not. Any suggestion ?
Thank you so much :-) Fabio.
append on list appends the item in place and does not return a new list. With the following:
elements2 = elements0.append(elements1)
elements2 being assigned the value None and elements0 now contains a new item, which is elements1
elements0[0] -> Paragraph("The Platypus0", styles['Heading1'])
elements0[1] -> Paragraph("Very <i>Special</i>!", styles['Normal'])
elements0[2] -> [Paragraph("The Platypus1", styles['Heading1']), Paragraph("Very <i>Special</i>!", styles['Normal'])
If you want to put the two texts together, use the concatenation
elements2 = elements0 + elements1
Is it possible to get the table from excel file and paste it to the word document saving its excel style? I didn't find adequate documentation about win32com and all its methods.
I've found a method PasteExcelTable, and I guess I should select the table from excel before invoking this method. I do the following:
from win32com import client
excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open("C:/word_file.docx")
book = excel.Workbooks.Open("C:/excel_file.xlsx")
sheet = book.Worksheets(1)
sheet.Range("A1:D20").Select # Selected the table I need to copy
doc.Content.PasteExcelTable(False, False, False)
And then it fails. I don't even know if I go the right direction.
Got it! There is no need to select anything, just straight copying
sheet.Range("A1:D20").Copy()
doc.Content.PasteExcelTable(False,False,False)
Since there is no documentation I had to try everything at random.