Read Excel worksheet using COM API by Python - python-2.7

I have used xlrd and xlwt earlier where its easy to read rows and column. I am in a process to convert my current excel read and write code(which is currently using xlrd and xlwt) to excel com api.
import win32com.client as win32
excel = win32.Dispatch('Excel.Application')
wbtemp = excel.Workbooks.Open(file path)
readtemp = wbtemp.Worksheets('Temp')
read_1 = readtemp.Cells(1,1)
print read_1
System User
used = readtemp.UsedRange
print used.Find('System User')
System User ## it shows System User is present in worksheet, wont give which cell
print used.Find('xyz')
None ## when its not found on worksheet
Currently above code is hard coded to Cell (1,1), but i am looking for flexible method like search for 'System User' in worksheet and get reply as Cell (1,1).

import win32com.client as win32
excel = win32.Dispatch('Excel.Application')
wbtemp = excel.Workbooks.Open(file path)
readtemp = wbtemp.Worksheets('Temp')
read_1 = readtemp.Cells(1,1)
print read_1
System User
used = readtemp.UsedRange
a = used.Rows.Find('System User')
print a.Address
$A$1 ## Thats what I was looking for..

Related

How to Read the Barcode in image using Python 3.6 without using Zbar

I am New to Barcode Reader i found some Tutorial about Zbar and which seems to not support in ZBAR. I like to raed the Barcode in a Image and extract the Data in it.
This is What is Actually Tried.
def detect_barcode(request):
try:
import pyqrcode
import zbarlight
qr = pyqrcode.create("HORN O.K. PLEASE.")
qr.png("download.png", scale=6)
import qrtools
from qrtools.qrtools import QR
from qrtools.qrtools import Image,BOM_UTF8
qr = qrtools.QR()
qr.decode("download.png")
True
print(qr.data);
qr.data
except Exception as e:
test = str(e)
I Need to Decode the Barcode and extract the Data. I don't like to use Zbar.
If it helps. We have a web browser that reads barcodes. No changes to your page are needed.
You can embed barcode scanning in your page and handle the result with JavaScript if you need more control.
Scan to Web

xlwings activate variable sheet name

I'm trying to perform two actions:
1) Check to see if a worksheet exists in a workbook using xlwings
2) Use a variable name to activate the worksheet using xlwings.
The worksheet name is a variable, so I can't use the sheets[0] option or sheets['name'] option.
import xlwings as xw
app = xw.apps.active
wb = app.books.active
key1 = 'BUS'
if key1 in wb:
sht = wb.sheets.activate(key1)
else:
sht = wb.sheets.add(key1)
I get the error:
AttributeError: 'Sheets' object has no attribute 'activate'
You should slightly rewrite your code to get this working. Tested this by opening a new Excel workbook and running the code a few times.
# python 3.7.3
# xlwings 0.15.8
import xlwings as xw
app = xw.apps.active
wb = app.books.active
key1 = 'BUS'
if key1 in [sh.name for sh in wb.sheets]:
sht = wb.sheets[key1]
else:
sht = wb.sheets.add(key1)
Changes:
You should iterate over the sheet names instead of the sheet objects
There is no need to activate a sheet in xlwings. As soon as you assign the sheet you want to work in to your sht variable, all actions will be performed on this sheet. You can also create a separate variable for every sheet (e.g. sht_bus, sht_train, ...)

Trying to scrape table off Yahoo Finance. Need to drive the website in order to select correct time frame

I am trying to scrape the historic data table for 5 YEARS from https://finance.yahoo.com/quote/^NYA/history?p=^NYA. When you initially go onto the website it shows you a year. I want to click on the arrow or the date, then click on "5Y" then click done. Wait for the page to refresh then scrape all the information. This is my code so far which does not work.
I have done something similar before but the problem with this website is that there are no ids or names for the objects I want to click onto so I do not know how to select them. (Va(m)! is the one of the class for the drop down arrow and 5_Y is the data-value for the 5Y option)
chromedriver = "/Users/Esi/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
url = 'https://finance.yahoo.com/quote/%5ENYA/history?p=%5ENYA'
print url
driver.get(url)
select = Select(driver.find_element_by_id('Va(m)!'))
select.select_by_value("5_Y")
###Please add in a line to select Done button###
time.sleep(10)
html = driver.page_source
soup = BeautifulSoup(html,"lxml")
tables = soup.findChildren('table')
#stock information in table indexed 1
print tables[1]
my_table = tables[1]
"""There are 7 columns Date -> Volume """
rows = my_table.findChildren(['th', 'tr'])
list_of_all =[]
for row in rows:
cells = row.findChildren('td')
for cell in cells:
value = cell.string
list_of_all.append(str(value.strip()))
# print list_of_all
num_rows = float(len(list_of_all))/float(7)
# print num_rows
driver.quit()
Give it a go. It should let you load the data for 5 years as you requested for.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("https://finance.yahoo.com/quote/%5ENYA/history?p=^NYA")
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "svg[class^=Va][data-icon=CoreArrowDown]"))).click()
item = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name=startDate]")))
item.clear()
item.send_keys("1/11/2013")
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[data-test=date-picker-menu] button[class*=Bgc]"))).click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button[data-reactid='25']"))).click() #it should click on the apply button
#driver.quit()

Python library to access a CalDAV server

I run ownCloud on my webspace for a shared calendar. Now I'm looking for a suitable python library to get read only access to the calendar. I want to put some information of the calendar on an intranet website.
I have tried http://trac.calendarserver.org/wiki/CalDAVClientLibrary but it always returns a NotImplementedError with the query command, so my guess is that the query command doesn't work well with the given library.
What library could I use instead?
I recommend the library, caldav.
Read-only is working really well with this library and looks straight-forward to me. It will do the whole job of getting calendars and reading events, returning them in the iCalendar format. More information about the caldav library can also be obtained in the documentation.
import caldav
client = caldav.DAVClient(<caldav-url>, username=<username>,
password=<password>)
principal = client.principal()
for calendar in principal.calendars():
for event in calendar.events():
ical_text = event.data
From this on you can use the icalendar library to read specific fields such as the type (e. g. event, todo, alarm), name, times, etc. - a good starting point may be this question.
I wrote this code few months ago to fetch data from CalDAV to present them on my website.
I have changed the data into JSON format, but you can do whatever you want with the data.
I have added some print for you to see the output which you can remove them in production.
from datetime import datetime
import json
from pytz import UTC # timezone
import caldav
from icalendar import Calendar, Event
# CalDAV info
url = "YOUR CALDAV URL"
userN = "YOUR CALDAV USERNAME"
passW = "YOUR CALDAV PASSWORD"
client = caldav.DAVClient(url=url, username=userN, password=passW)
principal = client.principal()
calendars = principal.calendars()
if len(calendars) > 0:
calendar = calendars[0]
print ("Using calendar", calendar)
results = calendar.events()
eventSummary = []
eventDescription = []
eventDateStart = []
eventdateEnd = []
eventTimeStart = []
eventTimeEnd = []
for eventraw in results:
event = Calendar.from_ical(eventraw._data)
for component in event.walk():
if component.name == "VEVENT":
print (component.get('summary'))
eventSummary.append(component.get('summary'))
print (component.get('description'))
eventDescription.append(component.get('description'))
startDate = component.get('dtstart')
print (startDate.dt.strftime('%m/%d/%Y %H:%M'))
eventDateStart.append(startDate.dt.strftime('%m/%d/%Y'))
eventTimeStart.append(startDate.dt.strftime('%H:%M'))
endDate = component.get('dtend')
print (endDate.dt.strftime('%m/%d/%Y %H:%M'))
eventdateEnd.append(endDate.dt.strftime('%m/%d/%Y'))
eventTimeEnd.append(endDate.dt.strftime('%H:%M'))
dateStamp = component.get('dtstamp')
print (dateStamp.dt.strftime('%m/%d/%Y %H:%M'))
print ('')
# Modify or change these values based on your CalDAV
# Converting to JSON
data = [{ 'Events Summary':eventSummary[0], 'Event Description':eventDescription[0],'Event Start date':eventDateStart[0], 'Event End date':eventdateEnd[0], 'At:':eventTimeStart[0], 'Until':eventTimeEnd[0]}]
data_string = json.dumps(data)
print ('JSON:', data_string)
pyOwnCloud could be the right thing for you. I haven't tried it, but it should provide a CMDline/API for reading the calendars.
You probably want to provide more details about how you are actually making use of the API but in case the query command is indeed not implemented, there is a list of other Python libraries at the CalConnect website (archvied version, original link is dead now).

How to read the contents of active directory using python-ldap?

My script is like this:
import ldap, sys
server = 'ldap://my_server'
l = ldap.initialize(server)
dn="myname#mydomain"
pw = "password"
l.simple_bind_s(dn,pw)
ldap.set_option(ldap.OPT_REFERRALS,0)
print "valid"
I am using Python 2.7 on windows.
Is there any method to read or get the contents of active directory?
You can do quite a lot also using win32com.client (which I had trouble finding documentation for). For example I've needed to resolve user email knowing his ADS_NAME_TYPE_NT4 formatted name (doman\jonjoe).
First of all you need to convert it to ADS_NAME_TYPE_1779 format (CN=Jeff Smith,CN=users,DC=Fabrikam,DC=com):
name_resolver = win32com.client.Dispatch(dispatch='NameTranslate')
name_resolver.Set(3, 'domain\\jonjoe')
ldap_query = 'LDAP://{}'.format(name_resolver.Get(1))
Once you have that you can simply call GetObject():
ldap = win32com.client.GetObject(ldap_query)
print(ldap.Get('mail'))
Tested with Python 3.2.5
You should realy need to read the documentation of python-ldap http://www.python-ldap.org/docs.shtml
You have a connection in your variable l, then you can do this.
l.con_search_s('dc=your,dc=base,dc=dit', ldap.SCOPE_SUBTREE, 'uid=*', ['uid', 'uidnumber'])
The above code, goint to search in to all the uid's entrys, for if entry, is going to get the uid and the uidnumbre attributes.