简体   繁体   English

将用户输入的数据从Excel工作表传输到Python脚本

[英]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. 我正在编写脚本,并且希望能够与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. 运行脚本后,我想打开一个excel工作表,让用户输入一些数据,在excel中进行一些基本计算,然后将计算出的数据和一些用户输入的数据返回到脚本中。

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. 我之所以这样做,是因为我想允许用户立即输入所有数据,而不必在提示后回答提示,并且因为我是Python的新手,甚至不能编写GUI。

Here's an example of what I'm trying to do: 这是我要执行的操作的一个示例:

Table 1 (range1 in an Excel worksheet): 表1(Excel工作表中的range1):

User enters Fraction and xa:aa data and excel calculates the blend. 用户输入分数和xa:aa数据,然后excel计算混合。 Blend info on xa:aa is returned to my python script is used in my script for further calculations. xa:aa上的混合信息返回到我的python脚本中,该脚本在我的脚本中用于进一步的计算。 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) 表2(同一Excel工作表中的range2)

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. 将数据输入excel并将其传输到脚本后,即可完成脚本。

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. Excel似乎是设置表条目数据的最简单方法,但是如果还有其他方法,请告诉我。 If it is Excel, how do I go about doing this ? 如果是Excel,我该怎么做?

You have many options. 您有很多选择。

Maybe you should look into VBA that way you can make your script in the excel document. 也许您应该以这种方式研究VBA,以便可以在excel文档中创建脚本。

You could also start learning Tkinter, so you make the interface in python right away. 您也可以开始学习Tkinter,因此可以立即在python中创建接口。

Personally I would do it in HTML. 就个人而言,我会用HTML来完成。 That way you can easy create an interface with inputs, and let javascript do the calculations. 这样,您可以轻松创建带有输入的接口,并让javascript进行计算。

But back to Python and EXCEL. 但是回到Python和EXCEL。

You could save the document as csv semicolon delimited. 您可以将文档另存为csv分号。

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 带有csv文件的带修饰符的字符串,带有某种for循环

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. 如果您想尝试使用HTML和javascript,它将看起来像这样。

<!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 JsFiddle

So you give the html elements id's, then you can acsess them from javascript. 因此,您可以给html元素id赋值,然后可以从javascript中访问它们。

You can also have javascript in a seperate .js file. 您也可以在单独的.js文件中使用javascript。

Then you just need to refer to it inside the script tag. 然后,您只需要在script标签内引用它即可。

<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. 如果输入文件不存在,它将写入一个虚拟文件(对此进行修改以适合),然后打开excel文件,并在用户关闭后读回数据框。 Replace excel_path with a path to your Excel install (I'm using LibreOffice to here). excel_path替换为您的Excel安装路径(我在这里使用LibreOffice)。

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 ,这是我编写的库,可以完全满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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