I have started using xlwings to create an excel tool which calls a python code. I think it is super useful and at the same time user-friendly as everybody is used to have excel as GUI.
Now to my problem: The tool works well. However, I am left with some formatting. Currently I am able to do some formatting (range(XX).number_format = XX ), but I have not managed to create my desired format.
I want to have comma separated numbers without decimals.
sht = xw.Book.caller().sheets[0]
sht.range('C:D').number_format = '0.00' (1)
sht.range('C:D').number_format = 'General' (2)
sht.range('C:D').number_format = '#’##0' (3)
(1): This works. However, numbers are not comma separated (as expected)
(2): Does not work. Python runs and runs, nothing happens. (same for 'Number')
(3): Produces desired results on my machine/ my excel version. However, on my friend's excel it looks different and does not produce the desired results anymore.
Thanks a lot in advance for your help.
In order to display the format in thousands and seperate by comma, I tried this,
number_format = "#,##0"
and it works perfectly in my case.
Related
I am currently working on a LabVIEW project which consists of 2 VIs(let it be A and B). I want to use output of A as input of the B. I am facing some problems while integrating the 2 VIs the output is an appended array which is also being stored in an empty file(given as input of A) whereas the input of B is a file path. Is there any conversion possible so that the values of appended array can be converted to file path? Can python script be used to automate the project, if yes then how?
I tried downloading LabVIEW 2020 but it is neither showing error nor there is any progress in the progress bar. Thus, the snippet attached here is from 2019 version.
I looked over your code.
When I tried your vi A, i got a file with 6 values seperated by a comma because that's my default setting. It looks like this:
Temperature,Pressure,Humidity
3,369,56,019,81,268
26,458,16,571,68,245
21,902,77,986,20,107
56,759,17,852,43,869
If this is the case in your generated file, use %.;%.3f as format for the writeSpreadsheet.vi
This forces the decimal point to be a point instead of a comma.
When I tried the code like this, it worked perfectly fine.
By the way, you don't have to use the flat sequence structure, just use your error wire and connect every vis from the beginning to the end.
Like this:
Additionally you should initialize the array that you shift in your while loop. If you use it one time, it might not be needed but if you call the vi a second time, the values might get stored there and the new values would just get appended.
Feel free to ask if you need more help :)
Here is an example of the .txt file that I have generated with your vi:
Temperature,Humidity,Pressure
38.802,66.355,4.347
64.646,68.519,60.982
71.997,56.336,96.116
20.744,24.189,75.689
85.731,25.168,20.026
65.386,67.284,97.049
I am really new in programming, sorry for the awful way of asking.
So for a class of kids I'm helping I am trying to make a program in python which must assign a random integer to 2 variables "A" & "B", once that is done, we must check if the ratio A/B yields an integer.
If that is the case, then we must have python print "A/B=~" so we must print this as a question without displaying the answer.
I achieved this by printing the variables as text once I checked the previously stated condition. So far everything is fine. I did this with a loop 5 times and got 5 different questions. I made it in such a way that changing I couple numbers I can make as many questions as I want.
Just to give an example I got:
14/7=
56/8=
35/5=
7/1=
81/3=
So the python part was basically done.
What I am unable to do and would appreciate if anyone could help me is the next part.
I have to take this results and and be able to make a pdf, if possible with latex, with the caveat that i don't like the idea of manually typing said results since for all the kids I have to do this around 180 times (30 times per kid). Is there a way to do this, since typing all manually in latex would take forever.
Yes, you can generate a latex by Python automatically with pylatex package. Here is a full example about the pylatex: PyLatex full examples
I write a small demo if I understand you correctly. These demo will create a latex named "test.tex" in the current directory, and an equation "a/b=0" is printed.
from pylatex import Document, Section, Subsection, Command,Package, Alignat
doc = Document(default_filepath='basic.tex', documentclass='article')
with doc.create(Subsection('Alignat math environment')):
with doc.create(Alignat(numbering=False, escape=False)) as agn:
agn.append(r'\frac{a}{b} &= 0 \\')
# trying to generate the tex and pdf, and do not clean the tex file after generating the pdf
doc.generate_pdf("test", clean_tex=False)
If you have tools like latexmk which can convert tex to pdf installed, then a pdf name test.pdf will also created. Otherwise you can use your latex editor open the test.tex file.
The conversion of xml to csv file, this is done by some code and the specifications that I have added.
As as result I get a csv file, once I open it I see some weird numbers that look something like this
1,25151E+21
Is there any way to eliminate this and show the whole numbers. The code itself that parses xml to csv is working fine so I’m assuming it is an excel thing.
I don’t want to go and do something manually every time I am generating a new csv file
Additional
The entire code can be found HERE and I have only long numbers in Quality
for qu in sn.findall('.//Qualify'):
repeated_values['qualify'] = qu.text
CSV doesn't pass any cell formatting rules to Excel. Hence if you open a CSV that has very large numbers in it, the default cell formatting will likely be Scientific. You can try changing the cell formatting to Number and if that changes the view to the entire number like you want, consider using the Xlsxwriter to apply cell formatting to the document while writing to Xlsx instead of CSV.
I often end up running a lambda on dataframes with this issue when I bring in csv, fwf, etc, for ETL and back out to XLSX. In my case they are all account numbers, so it's pretty bad when Excel helpfully overrides it to scientific notation.
If you don't mind the long number being a string, you can do this:
# First I force it to be an int column as I import everything as objects for unrelated reasons
df.thatlongnumber = df.thatlongnumber.astype(np.int64)
# Then I convert that to a string
df.thatlongnumber.apply(lambda x: '{:d}'.format(x))
Let me know if this is useful at all.
Scientific notation is a pain, what I've used before to handle situations like this is to cast it into a float and then use a format specifier, something like this should work:
a = "1,25151E+21"
print(f"{float(a.replace(',', '.')):.0f}")
>>> 1251510000000000065536
i am trying to set cell format to display 2 decimals, i need it to show 2 decimals, somehow when i use different office application to open, it gives mixed results, i am new to openpyxl (using latest 2.5.1), i have go through the documentation, setting the format seems pretty straight forward
what i have done for setting format is:-
ws.column_dimensions['F'].number_format = '#,##0.00'
ws.column_dimensions['G'].number_format = '#,##0.00'
not too sure am i miss out any?
For the attached image, it shows Open Office and Libre Office able to show the two decimals i needed, somehow WPS and MS Excel unable to show two decimals, a quick check on all the above format cell (through right click on that cell), Open Office and Libre Office is in Number format, somehow WPS and MS Excel is in General format
note: i have tried setting more decimals, e.g.: 3 decimals or more, still Open Office and Libre showing the specified decimals without problem, but WPS and MS Excel dont
i have found a work around, which i need to set every single cell manually for formatting it to two decimals, seems working when using WPS and MS Excel to open
for row in range(1, rows):
ws["F{}".format(row)].number_format = '#,##0.00'
ws["G{}".format(row)].number_format = '#,##0.00'
After doing the suggested, it still did not work for me.
Seems like MS Excel still sees the cell value as String.
So I tried to do a manual conversion of each cell before formatting:
for row in range(1, rows):
ws["F{}".format(row)].value = float(ws["F{}".format(row)].value)
ws["F{}".format(row)].number_format = '#,##0.00'
Gladly, it worked. I'm using Python 2.7.6. MS Excel Version 1808 64 bit.
You could use the round() function in python to round the figures there before writing them to their cells in excel. I would recommend adding the columns from excel to lists and then iterating through the lists using a for-loop
for i in list:
round(i, 2) #Rounds each element of the list to two decimal places
Hope this helps
I'm importing data coming from excel files that come from another office.
In one of the columns, for each cell, I have lists of numbers used as tags. These were manually inserted, by different people and (my guess) using computers with different thousands settings, so the result is very heterogeneous.
As an example I have:
tags= ['205', '306.3', '3,206,302','7.205.206']
If this was a CSV file (I tried converting one single file to check), using
pd.read_csv(my_file,sep=';')
would give me exactly the above mentioned list.
Unfortunately as said, we're talking about excel files (plural) and I have to deal with it, and using
pd.read_excel(my_file,sheetname=my_sheet,encoding='utf-16',converters{'my_column':str})
what I get instead is:
tags= ['205', '306.3', '3,206,302','7205206']
As you see, whenever the number can be expressed logically in thousands (so, not the second number in my list) the dot is recognised as a thousands separator and I get a single number, instead of three.
I tried reading documentation, and searching on stackoverflow and google, but the keywords to describe this problem are too vague and I didn't find a viable solution, yet.
How can I get the right list using excel files?
Thanks.
This problem is likely happening because pandas is running their number parser before their date parser.
One possible fix is to add a thousands separator. For example, if you are actually using ',' as your thousands separator, you could add thousands=',' in your excel reader:
pd.read_excel(my_file,sheetname=my_sheet,encoding='utf-16',thousands=',',converters{'my_column':str})
You could also pick an arbitrary thousand separator that doesn't exist in your data to make the output stay the same if thousands=None (which should be the default according to documentation), doesn't already deal with your problem. You should also make sure that you are converting the fields to str (in which case using thousands is kind of redundant, as it's not applied to trings either way).
EDIT:
I tried using the following dummy data ('test.xlsx'):
a b c d
205 306.3 3,206,302 7.205.206
and with
dataf = pandas.read_excel('test.xlsx', header=0, converters={'a':str, 'b':str,'c':str,'d':str})
print(dataf.to_string)
I got the following output:
Columns: [205, 306.3, 3,206,302, 7.205.206]
Which is exactly what you were looking for. Are you sure you have the latest version of pandas and that you are in fact not using converters = {'col':int} or float in your converters keyword?
As it stands, it sounds like you are either converting your fields to numeric (int or float), or there is a problem elsewhere in your code. The pandas read_excel seems to work as described, and I can get the results you specified with the code specified above. In other wods: Your code should work, if it doesn't it might be due to outdated pandas version, other parts in your code or even problems with the source data. As it stands, it's not possible to answer your question further with the information you have provided.