xlwings set_mock_caller() return None - python-3.x

Windows 10, Python 3.6, xlwings 0.27.8
When trying to debug my code outside of RunPython, I keep stumbling on the following issue, for example:
import xlwings as xw
xlsx_file = 'anExcelFile.xlsm'
xlwx = xw.book(xlsx_file).set_mock_caller()
From there, I am hoping to be able to use xlsw as normally as such if I had used the routine from RunPython, but now, typing xlsw returns None
However, if i do:
xlsx = xw.book(xlsx_file).set_mock_caller
then xlsx contains: <Book ['anExcelFile.xlsm]>
but still, xlsx() returns None.
Any lead on what I am getting wrong would help, thanks!

Finally understood my issue.
As explained in xlwings, the code sequence should read as follows:
import xlwings as xw
xlsx_file = 'anExcelFile.xlsm'
xw.book(xlsx_file).set_mock_caller()
# Sets the Excel file which is used to mock xw.Book.caller()
# when the code is called from Python and not from Excel via RunPython.
# and then:
xlsx = xw.Book.caller()
Now, xlsx returns: <Book [anExcelFile.xlsm]>

Related

What are Python3 libraries which replace "from scikits.audiolab import Format, Sndfile"

Hope you'll are doing good. I am new to python. I am trying to use audio.scikits library in python3 verion. I have a working code version in 2.7(with audio.scikits) . While I am running with python3 version I am getting the Import Error: No Module Named 'Version' error. I get to know that python3 is not anymore supporting audio.scikits(If I am not wrong). Can anyone suggest me replacing library for audio.scikits where I can use all the functionalities like audio.scikits do OR any other solution which might helps me. Thanks in advance.
2.7 Version Code :
from scikits.audiolab import Format, Sndfile
from scipy.signal import firwin, lfilter
array = np.array(all)
fmt = Format('flac', 'pcm16')
nchannels = 1
cd, FileNameTmp = mkstemp('TmpSpeechFile.wav')
# making the file .flac
afile = Sndfile(FileNameTmp, 'w', fmt, nchannels, RawRate)
#writing in the file
afile.write_frames(array)
SendSpeech(FileNameTmp)
To check entire code please visit :Google Asterisk Reference Code(modifying based on this code)
I want to modify this code with python3 supported libraries. Here I am doing this for Asterisk-Microsoft-Speech To Text SDK.
Firstly the link code you paste is Asterisk-Google-Speech-Recognition, it's not the Microsoft-Speech-To-Text, if you want get a sample about Microsoft-Speech-To-Text you could refer to the official doc:Recognize speech from an audio file.
And about your problem you said, yes it's not completely compatible, in the github issue there is a solution for it, you could refer to this comment.

Not able to read xlsb file using Python [duplicate]

There are many questions on this, but there has been no simple answer on how to read an xlsb file into pandas. Is there an easy way to do this?
With the 1.0.0 release of pandas - January 29, 2020, support for binary Excel files was added.
import pandas as pd
df = pd.read_excel('path_to_file.xlsb', engine='pyxlsb')
Notes:
You will need to upgrade pandas - pip install pandas --upgrade
You will need to install pyxlsb - pip install pyxlsb
Hi actually there is a way. Just use pyxlsb library.
import pandas as pd
from pyxlsb import open_workbook as open_xlsb
df = []
with open_xlsb('some.xlsb') as wb:
with wb.get_sheet(1) as sheet:
for row in sheet.rows():
df.append([item.v for item in row])
df = pd.DataFrame(df[1:], columns=df[0])
UPDATE:
as of pandas version 1.0 read_excel() now can read binary Excel (.xlsb) files by passing engine='pyxlsb'
Source: https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html
Pyxlsb indeed is an option to read xlsb file, however, is rather limited.
I suggest using the xlwings package which makes it possible to read and write xlsb files without losing sheet formating, formulas, etc. in the xlsb file. There is extensive documentation available.
import pandas as pd
import xlwings as xw
app = xw.App()
book = xw.Book('file.xlsb')
sheet = book.sheets('sheet_name')
df = sheet.range('A1').options(pd.DataFrame, expand='table').value
book.close()
app.kill()
'A1' in this case is the starting position of the excel table.
To write to xlsb file, simply write:
sheet.range('A1').value = df
If you want to read a big binary file or any excel file with some ranges you can directly put at this code
range = (your_index_number)
first_dataframe = []
second_dataframe = []
with open_xlsb('Test.xlsb') as wb:
with wb.get_sheet('Sheet1') as sheet:
i=0
for row in sheet.rows():
if(i!=range):
first_dataframe.append([item.v for item in row])
i=i+1
else:
second_dataframe.append([item.v for item in row])
first_dataframe = pd.DataFrame(first_dataframe[1:], columns=first[0])
second_dataframe = pd.DataFrame(second_dataframe[:], columns=first.columns)
To be able to read xlsb files, it is necessary to have openpyxl installed.
As per https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html#pandas.read_excel
engine: str, default None
If io is not a buffer or path, this must be set to identify io. Supported engines: “xlrd”, “openpyxl”, “odf”, “pyxlsb”. Engine compatibility :
“xlrd” supports old-style Excel files (.xls).
“openpyxl” supports newer Excel file formats.
“odf” supports OpenDocument file formats (.odf, .ods, .odt).
“pyxlsb” supports Binary Excel files.
Changed in version 1.2.0: The engine xlrd now only supports old-style .xls files.
When engine=None, the following logic will be used to determine the engine:
If path_or_buffer is an OpenDocument format (.odf, .ods, .odt), then odf will be used.
Otherwise if path_or_buffer is an xls format, xlrd will be used.
Otherwise if openpyxl is installed, then openpyxl will be used.
Otherwise if xlrd >= 2.0 is installed, a ValueError will be raised.
Otherwise xlrd will be used and a FutureWarning will be raised. This case will raise a ValueError in a future version of pandas.
xlsb reading without index_col:
import pandas as pd
dfcluster = pd.read_excel('c:/xml/baseline/distribucion.xlsb', sheet_name='Cluster', index_col=0, engine='pyxlsb')

xlwings : Object Required

I'm a newbie into both python and xlwings. So the story is,
I need a custom function needs to be used in Excel. Since I have no clue about VB scripts, I decided to write a function in python and import it in excel using xlwings.
I installed xlwings using the pip command. I added the addin to excel
by the procedure given in xlwings support forum.
I created an excel file, say " Test.xlsm". I created a python file in
the same name "Test.py" (File is in same folder only)
I wrote my function in the python
import xlwings as xl
#xl.func
def exponent(x,y):
#the function is an example only. I tried this for practicing and it is also not working
z=x**y
return z
I opened excel, imported the functions using import function in
xlwings addin. I found no errors in importing the functions
I called the functions from the excel cell,
"=exponent(A1,B1)"
Instead of getting a result, I'm getting "Object Required"
I don't know what went wrong?
Any ideas what I'm missing? Forgive me for the basic question.
You need to add the Reference in VBA.
Open up the Developer console (Alt-F11)
Click on Tools -> References and select xlwings

using xlwt to edit excel file then save it, but get nothing changed

I am a new learner.Maybe it's A Stupid Question. I use below code try to write something in sheet :'new' in 'or.xlsx'. but after i finised ran my code. nothing was been writer in that sheet. No error was pop up.Here is the code :
from xlrd import open_workbook
import xlwt
wb = xlwt.Workbook('D:\Work\xxx\xx\python\or.xlsx')
ws = wb.add_sheet(u'new', cell_overwrite_ok=True)
ws.write(0, 0, u'523123')
wb.save('or.xlsx')
IDE: Pycharm
python 2.7.13
drop the first line, xlrd is not used in the remainder of the code.
xlwt writes XLS files, not XLSX.
The first arg of xlwt.Workbook is NOT a file path! Pls review the docs.

Attribute error while trying to refresh Pivot Tables with Python 2.7

I have tried to find the answer online but only got confused.
I am a windows user, have Python 2.7 and work with Excel 2010 files saved on sharepoint, trying to automate the data extraction. Basically, my solitaire-long program opens the files one by one, extract the data and saves them into a new xl file.
Hitherto I have used xlwt and xlrd and everything was going pretty smoothly. But now I have encountered a file xlsm that contains the pivot tables that need to be refreshed every time . I have googled it up and found the code:Python: Refresh PivotTables in worksheet
The problem is it does not work for me at all... I keep getting attribute errors like
AttributeError: .Open
I have noticed that the syntax differs substantially, too (wb.Sheets.Count versus wb.nsheets). With win32com I am not able even to iterate through the sheets of a workbook... I just do not have a clue what is a problem - the Python version, importing problem or whatever...
The thing that I cannot find in xlrd/xlwt: ws.PivotTables(j).PivotCache().Refresh() - if I am not mistaken, the problem is that with xlrd/xlwt I am not actually opening Excel file, so probably it is not possible to refresh data using them... Alas, moving to win32com.client hasn't helped...
Any suggestions or links? :) I am probably gonna add an automatic update (refresh) to a VBA code of the xl file in question, but I'd rather not change the files, but my code :)
Edit: I paste my code below, along with an error I keep getting:
the below thing, copied from someone else's code, does not work, returning an AttributeError: Property 'Excel.Application.Visible' can not be set.:
import win32com.client
import os
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("//some_dir.xlsm")
xl.Visible = True
wb.RefreshAll()
xl.Quit()
Alas when I try to merge it into a program that uses also xlrd and xlwt it does not work...
from copy import deepcopy
from xlrd import open_workbook
from xlutils.copy import copy as copy
from xlwt import *
from datetime import *
#some definitions here...
rb = open_workbook('my_template.xlsx')
wb = copy(rb)
sheet_1 = wb.get_sheet(0)
sheet_2 = wb.get_sheet(1)
#now the code that evaluates the dates:
import datetime
ys = raw_input('year in yyyy format:\n')
ms = raw_input('month in mm format:\n')
ds = raw_input('day in dd format:\n')
#here the definitions concerning dates are called, all in xlwt and xlrd
#now other files are being opened and data extracted and written into sheet_1 and sheet_2
#now it's time for refreshments ;) - I wanted to 1. open and update the file with win32com, #close it and 2. with xlrd get the data from the updated file:
#refreshing all (preparing file)
import win32com.client
import os
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("some_dir.xlsm") #it is a shared file saved in intranet
xl.Visible = True
wb.RefreshAll()
xl.Quit()
print 'file refreshed'
file = open_workbook("some_dir.xlsm")
row_sheet1 = 176
row_sheet2 = 248
for sheet in file.sheets():
print sheet.name
#... the rest of the code ensues
The error again is: AttributeError: Property 'Excel.Application.Visible' can not be set.
I guess I am not supposed to use xlrd and win32com.client simultanously and my whole idea is just soooo wrooong? ;) But why does it not work "alone", I mean the first, short code?

Resources