简体   繁体   中英

Transferring user entered data from an Excel worksheet to a Python Script

I'm writing a script and I would like to be able to interact with MS Excel. Once I run the script, I would like to open up an excel worksheet, have the user enter some data, do some basic calcs in excel, and then return the calculated data and some of the user entered data to the script.

I'm doing this because I'd like to allow the user to enter all the data at once and not have to answer prompt after prompt and also because I'm new to Python and not even close to being able to write a GUI.

Here's an example of what I'm trying to do:

Table 1 (range1 in an Excel worksheet):

User enters Fraction and xa:aa data and excel calculates the blend. Blend info on xa:aa is returned to my python script is used in my script for further calculations. The data entry table is actually longer (more rows of data entry) but just showing enough of a subset to give a feel for what I'm trying to do:

Stream       1   2    3  4  5   Blend
Fraction    10% 60% 20% 10       100%
xa          100 150 175 57       135.0
yg          30.7 22 18  12.2     25.6
aa          210 425 375 307      352.2

Table 2 (range2 in the same Excel worksheet)

User enters all data and everything is returned to script for further calculations:

        Min Max Incr            
temp    45  60  5           
press   7.2 7.8 0.2         
cf      1   5   1           

Once the data is entered into excel and transferred to the script, I complete the script.

How do I go about doing this ? Excel seems like the easiest way to set up table entry data but if there is another way, please let me know. If it is Excel, how do I go about doing this ?

You have many options.

Maybe you should look into VBA that way you can make your script in the excel document.

You could also start learning Tkinter, so you make the interface in python right away.

Personally I would do it in HTML. That way you can easy create an interface with inputs, and let javascript do the calculations.

But back to Python and EXCEL.

You could save the document as csv semicolon delimited.

import os
with open('yourcsv.csv','r') as f:
    contents = f.read().splitlines()

values = []

for row in range(0,len(contents),1): 
    values += contents[row].split(';')

Now you got your table in a multidimensional list. Do some calculations.

now you need to append the result as a ; delimeted string to the csv file, with some kind of for loop

file = open('yourcsv.csv','a')
file.write(results)
file.close()

If you want to try with HTML and javascript, it would look something like this.

<!DOCTYPE html>
<html>
    <head>
    <title>Optional</title>
    <meta charset='UTF-8'>
    <script>
        function calc(){
            var val1 = parseFloat(document.getElementById('value1').value);
            var val2 = parseFloat(document.getElementById('value2').value);
            var res = val1+val2;
            var resDiv = document.getElementById('result');
            resDiv.innerHTML = parseFloat(res,2);
        }
    </script>
    </head>
    <body>
        <input type='text' id='value1'>
        <input type='text' id='value2'>
        <br>
        <button onClick='calc()'>Calculate</Button>
        <br>
        <div id='result'></div>
    </body>
</html>

JsFiddle

So you give the html elements id's, then you can acsess them from javascript.

You can also have javascript in a seperate .js file.

Then you just need to refer to it inside the script tag.

<script src='yourScript.js'></script>

Here's a potential approach using pandas. If the input file doesn't exist, it writes a dummy file (modify this to suit), then opens the excel file, and reads back into a dataframe once the user has closed. Replace excel_path with a path to your Excel install (I'm using LibreOffice to here).

import os
import subprocess

import pandas as pd

input_file = 'input.xlsx'
excel_path = 'soffice'

#############
# setup stuff
#############

if not os.path.isfile(input_file):
    input_template = pd.DataFrame(columns=['1','2','3','4'])
    # any additional code to set up space for user to input values

    input_template.to_excel(input_file)
else:

# call excel and open the input file
subprocess.call([excel_path, input_file])

# read modified input into DataFrame
excel_input = pd.read_excel(input_file)

################
# body of script
################

看看xlwings ,这是我编写的库,可以完全满足您的需求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM