I am trying to find the last cell in an excel worksheet by Python win32 module, but somehow it doesn't seem to recognize End(xlDown).
Program line-
LastRow = WBName.Sheets("Sheet1").Cells(2,2).End(xlDown).Row
The error-
NameError: name 'xlDown' is not defined
Thanks in advance for any help.
win32c = win32.constants
XlApp.Visible = 1
wb = XlApp.Workbooks.Open(Input)
ws = wb.ActiveSheet
excel.DisplayAlerts = False
lr = XlApp.Cells(ws.Rows.Count, "A").End(win32c.xlShiftUp).Row
print(lr)
or
def LastRow(WS,COL):
return WS.Cells(WS.Rows.Count, COL).End(win32c.xlShiftUp).Row
print(LastRow(ws,"a"))
Related
Code :
wb = Workbook()
sdwbb = load_workbook(sdpath)
filename = os.path.basename(sdpath)
bulan = "September"
try:
sdp = sdwbb[bulan]
except:
sdwbb.create_sheet(bulan)
wb.save(filename)
time.sleep(0.5)
sdp = sdwbb[bulan]
cell_one = sdp['F1']
cell_one.value = 'test'
sdwbb.save(filename)
for your information I doesn't get any error but its doesn't write anything cell f1 sheet September
what I trying to do is to write on specific workbook ,sheet ,and cell
This is my code to write "test" in cel F1 (in the current sheet) in the file test.xlxs in the same folder:
from openpyxl import Workbook, load_workbook
wb = load_workbook("test.xlsx")
ws = wb.active
ws["F1"] = "test"
wb.save("test.xlsx")
print("done")
It's as easy as that :).
Also, you should devenitly check out the documentation of openpyxl: https://openpyxl.readthedocs.io/en/stable/tutorial.html#create-a-workbook
I am currently writing a script that requires me to update data in an Excel sheet and run a macro. After running the macro, I am trying to save the file using win32, in order to be able to run through a similar process again. However, I have linked everything back to a weird issue with win32 and openpyxl. It seems that if I run the macro using win32, save the file and open it, everything looks exactly how it should. But if I then use openpyxl to add something to that file after running the macro, the entire results from the macro are then deleted. For example, the macro fills in cells A4:H23 with the correct data, but then after saving with win32 and reopening and editing with openpyxl, if I try to add any value to cell A3 afterwards and open up the file, the only thing that shows is the value in A3 and nothing that the macro should have done. I can open the sheet manually and add the number and resave it perfectly fine, but when I use openpyxl to do so, it clears all the macro results. I have included my code below for reference. Any help would be appreciated.
from openpyxl import load_workbook
import os
import win32com.client
import re
import time
Macro1 = r"C:\Users\...\Documents\Macro1Demo.xlsm"
Macro2 = r"C:\Users\...\Documents\Macro2Demo.xlsm"
MiddleManTest = r"C:\Users\...\Documents\MiddleManTest.xlsm"
MiddleMan2 = r"C:\Users\...\Documents\MiddleMan2.xlsm"
DistrictList = r"C:\Users\...\Documents\DistrictList.xlsx"
Macro1WB = load_workbook(filename = Macro1, keep_vba = True)
Macro2WB = load_workbook(filename = Macro2, keep_vba = True)
MM2WB = load_workbook(filename = MiddleMan2, keep_vba = True)
ListWB = load_workbook(filename = DistrictList, keep_vba = True)
ListSheet = ListWB['Sheet1']
M1Sheet = Macro1WB['Entry']
M2Sheet = Macro2WB['Raw']
for i in range(2,3):
Macro1WB['Entry']['A2'].value = ListWB['Sheet1']['A' + str(i)].value
Macro1WB['Entry']['B2'].value = ListWB['Sheet1']['B' + str(i)].value
OrgName = Macro1WB['Entry']['A2'].value
DistrictName = Macro1WB['Entry']['B2'].value
Macro1WB.save(Macro1)
SimpleOrgName = re.sub('[/\:*?<>|"]','',OrgName)
SimpleDistrictName = re.sub('[/\:*?<>|"]','',DistrictName)
NewFileName = SimpleOrgName + "(" + SimpleDistrictName + ")"
print(Macro1WB['Entry']['A2'].value,Macro1WB['Entry']['B2'].value)
print("Org/District Copied.")
if os.path.exists(r"C:\Users\...\Documents\Macro1Demo.xlsm"):
xl = win32com.client.Dispatch("Excel.application")
xl.visible = True
workbook = xl.Workbooks.Open(os.path.abspath(r"C:\Users\...\Documents\Macro1Demo.xlsm"))
xl.Application.Run("Macro1Demo.xlsm!Module1.AdvancedFilter")
print("Data filtered.")
workbook.SaveAs(MiddleMan2)
xl.Application.Quit()
MM2WB['Entry']['A3'] = i
MM2WB.save(MiddleMan2)
Several columns of excel documents have been grouped and hidden.
How to use win32.com to expand them?
excel_path = str(Path.cwd() / 'data.xlsx')
excel = win32com.client.DispatchEx("Excel.Application")
excel.Visible = True
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(excel_path)
wb.RefreshAll()#refresh data from external source
excel.CalculateUntilAsyncQueriesDone()
excel.DisplayAlerts = False
ws = wb.Worksheets('Sheet1')
ws.Outline.ShowLevels(ColumnLevels=1)# Try to expand all columns in worksheet, is this correct?
Thanks.
Try this one:
ws.Columns.EntireColumn.Hidden=False
This is the code I'm using but, If I use a function in excel, python prints only the function and not it's output. I imagine this is normally fixed using an intermediary like notebook, but the Arabic typeface does not transfer over. Any help you could give would be greatly appreciated.
Thanks,
William M. Hollingsworth
rom openpyxl import load_workbook
def main():
wb = load_workbook(filename ="F:\\Quran Gematria.xlsx", read_only=True)
ws = wb['Sheet1']
bigdict = {}
rowcount = 0
for row in ws.rows:
rowdict = {}
rowdict['words'] = row[0].value
rowdict['sum'] = row[1].value
rowdict['prime']=row[2].value
rowdict['form'] = row[3].value
rowdict['verse'] = row[4].value
bigdict[rowcount] = rowdict
rowcount += 1
for wordkey in bigdict:
if(bigdict[wordkey]['form'] ==74):
print(bigdict[wordkey])
main()
set data_only to True when load workbook:
import openpyxl
wb = openpyxl.load_workbook('forecast.xlsx', data_only=True)
I am trying to activate multiple excel worksheets and write to both multiple sheets within both workbook(s) using python and openpyxl. I am able to load the second workbook f but I am unable to append cell G2 of my second workbook with the string Recon
from openpyxl import Workbook, load_workbook
filename = 'sda_2015.xlsx'
wb = Workbook()
ws = wb.active
ws['G1'] = 'Path'
ws.title = 'Main'
adf = "Dirty Securities 04222015.xlsx"
f = "F:\\ana\\xlmacro\\" + adf
wb2 = load_workbook(f)
"""
wb22 = Workbook(wb2)
ws = wb22.active
ws['G1'] = "Recon2"
ws.title = 'Main2'
"""
print wb2.get_sheet_names()
wb.save(filename)
I commented out the code which is broken
Update
I adjusted my code with the below answer. The value in cell H1 is written onto wb2 in column H, but for some reason the column is hidden. I have adjusted the column to other columns but still I have seen the code hide multiple columns. There are also occurences when the code executes and titles ws2 as Main21 but the encoded value is Main2
from openpyxl import Workbook, load_workbook
filename = 'sda_2015.xlsx'
wb1 = Workbook()
ws1 = wb1.active
ws1['G1'] = 'Path'
ws1.title = 'Main'
adf = "Dirty Securities 04222015.xlsx"
f = "F:\\ana\\xlmacro\\" + adf
wb2 = load_workbook(f)
ws2 = wb2.active
ws2['H1'] = 'Recon2'
ws2.title = 'Main2'
print wb2.get_sheet_names()
wb1.save(filename)
wb2.save(f)
If you have two workbooks open, wb1 and wb2, you'll also need different names for the various worksheets: ws1 = wb1.active and ws2 = wb2.active.
If you're working with a file with macros, you'll need to set the keep_vba flag to True when opening it in order to preserve the macros.
I had experienced the same thing with hidden cells. Eventually, I unpacked the Excel file and looked at the raw XML to find out that not all of the columns had a dimension for width. Those without a width were being by Excel.
A quick fix is to do something like this...
for col in 'ABCDEFG':
if not worksheet.column_dimensions[col].width:
worksheet.column_dimensions[col].width = 10