I have exported a dataframe to Excel using xlwings and am trying to format it as a table. I want to apply the "None" style but can't figure out how to specify the "None."
This line works:
table = sheet.tables.add(source=sheet["A1"].expand(), name = 'TableName', table_style_name = "TableStyleLight1")
But instead of "TableStyleLight1" I want "None". I have tried "", '', 0, "None" and none of them work.
You can use .api to access the native object, and clear the formatting after creating the table:
table = sheet.tables.add(source=ws.range('I20:N40'), name='UnformattedTable')
sheet.api.ListObjects('UnformattedTable').TableStyle = "" # Windows specific
But as mentioned in the comments, it doesn't seem to be supported using tables.add directly.
xlwings has a missing feature page with an example on using .api. Note the above example is for windows, the api for mac is slightly different.
Related
Working on a batch exporter that is able to export different objects into different files at the same time (with one button).
I am using cmds.file or mel.eval('FBXExport') to export the fbx files. I got trouble with exporting a specific object based on its name. Like no matter whether I select anything or how many objects I select, it only exports the object named 'cube'.
Is there any way to achieve this goal?
The python code I used to export. They can only export my selected objects.
cmds.file(filepath, force = True, options = "v = 0", type = "FBX export", exportSelected = True)
mel.eval('FBXExport -f "%s" -s'%(filepath) )
When I used the code above to export, it exports all objects I selected, not the one named 'cube'.
I solved the problem right after I asked this question! just adding cmds.select command.
for obj in sel:
**cmds.select(obj)**
cmds.file(filepath, force = True, options = "v = 0", type = "FBX export", exportSelected = True)
Hope it can help other people who have the same question.
I'm trying to create a Python script (I'm using Python 3.7.3 with UTF-8 encoding on Windows 10 64-bit with Microsoft Office 365) that exports user selected worksheets to PDF, after the user has selected the Excel-files.
The Excel-files contain a lot of different settings for page setup and each worksheet in each Excel-file has a different page setup.
The task is therefore that I need to read all current variables regarding page setup to be able to assign them to the related variables for export.
The problem is when I'm trying to get Excel to return the current print area of the worksheet, which I can't figure out.
As far as I understand I need to be able to read the current print area, to be able to set it for the export.
The Excel-files are a mixture of ".xlxs" and ".xlsm".
I've tried using all kind of different methods from the Excel VBA documentation, but nothing has worked so far e.g. by adding ".Range" and ".Address" etc.
I've also tried the ".UsedRange", but there is no significant difference in the cells that I can search for and I can't format them in a specific way so I can't use this.
I've also tried using the "IgnorePrintAreas = False" variable in the "ExportAsFixedFormat"-function, but that didn't work either.
#This is some of the script.
#I've left out irrelevant parts (dialogboxes etc.) just to make it shorter
#Import pywin32 and open Excel and selected workbook.
import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = False
wb = excel.Workbooks.Open(wb_path)
#Select the 1st worksheet in the workbook
#This is just used for testing
wb.Sheets([1]).Select()
#This is the line I can't get to work
ps_prar = wb.ActiveSheet.PageSetup.PrintArea
#This is just used to test if I get the print area
print(ps_prar)
#This is exporting the selected worksheet to PDF
wb.Sheets([1]).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path, Quality = 0, IncludeDocProperties = True, IgnorePrintAreas = False, OpenAfterPublish = True)
#This closes the workbook and the Excel-file (although Excel sometimes still exists in Task Manager
wb.Close()
wb = None
excel.Quit()
excel = None
If I leave the code as above and try and open a test Excel-file (.xlxs) with a small PrintArea (A1:H8) the print function just gives me a blank line.
If I add something to .PrintArea (as mentioned above) I get 1 of 2 errors:
"TypeError: 'str' object is not callable".
or
"ps_prar = wb.ActiveSheet.PageSetup.PrintArea.Range
AttributeError: 'str' object has no attribute 'Range'"
I'm hoping someone can help me in this matter - thanks, in advance.
try
wb = excel.Workbooks.OpenXML(wb_path)
insead of
wb = excel.Workbooks.Open(wb_path)
My problem was with a german version of ms-office. It works now. Check here https://social.msdn.microsoft.com/Forums/de-DE/3dce9f06-2262-4e22-a8ff-5c0d83166e73/excel-api-interne-namen?forum=officede
I tried really hard to find how to do these simple lines of VBA code in Python via win32com but I couldn't find how to execute it properly :
ActiveSheet.PivotTables("PivotTable1").PivotFields("Quarters").ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields("Effective deadline"). _
PivotFilters.Add2 Type:=xlBefore, Value1:="10/10/2017"
When running these lines :
from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wb = excel.Workbooks.Open('myfile.xlsx')
ws = wb.Worksheets('MySheet')
ws.PivotTables(1).PivotFields("Quarters").PivotFilters('Add2', 'xlBefore', '10/10/2017')
I end up with an 'Invalid number of parameters' so I guess I'm quite close but can't find the documentation to complete my code
Has anyone ever managed to do this kind of work ?
You are calling the wrong method. You should call .Add2 after the PivotFilters property:
ws.PivotTables(1).PivotFields("Effective deadline").ClearAllFilters()
ws.PivotTables(1).PivotFields("Effective deadline").PivotFilters.Add2(31, None, '10/10/2017')
Also, notice that you need to specify the XlPivotFilterType Enumeration according to the type of filter you want to apply (in this case xlBefore = 31)
The snippet below works fine (including the link) - except that this is a big table with lots of links and the final sheet is loaded with warnings ("The number in this cell is formatted as text or preceded by an apostrophe"). This is true but the write method wont accept an integer in the last parameter and write_number() doesn't seem to accept hyperlinks arguments like the write method. The warning can be patched manually in excel but that is not really an option. I would prefer to have it formatted as an integer but would be satisfied if I could just stop getting all of the warnings in the resulting Excel file. I tried various format settings and tried various options including putting '{'strings_to_numbers': True}' in the workbook creation.
stream = StringIO()
workbook = xlsxwriter.Workbook(stream, {'strings_to_numbers': True})
integer_format = workbook.add_format({'num_format': '#,##0'})
linkable_sheet = workbook.add_worksheet('linkable_sheet')
main_sheet = workbook.add_worksheet('main_sheet')
main_sheet.add_table(0,0,2,2)
main_sheet.write(1, 0, 'internal:linkable_sheet!A1', integer_format, '100')
workbook.close()
stream.seek(0)
return stream.getvalue()
Thanks
XlsxWriter probably should probably accept integer/floats in situations like this. I'll look into allowing that in future versions.
In the meantime the recommended workaround in the documentation is to write the url with a dummy (or no) string and then overwrite the string part of the url with whatever type/data you wish.
Try modifying your example as follows:
...
main_sheet.write(1, 0, 'internal:linkable_sheet!A1', integer_format)
main_sheet.write(1, 0, 100, integer_format)
...
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.