首页 > 解决方案 > 在 Windows 窗体中使用 xlrd 和 Ironpython

问题描述

我对 Windows 窗体和 Ironpython 很陌生,我必须连接一个 python 脚本来读取 excel 文件的列值并将列表返回到 Windows 窗体,所以我为此做了一个类:

class Python_Script
    {
        private ScriptEngine engine;
        private ScriptScope scope;
        private ScriptSource source;
        public Python_Script(string name)
        {
            engine = Python.CreateEngine();
            scope = engine.CreateScope();
            string str = @"script_route" + name;
            engine.ExecuteFile(@str, scope);
        } 

        public List<string> Col_Values(int sheet, int col)
        {
            List<string> result;
            dynamic col_values = scope.GetVariable("Col_Values");
            result = col_values(sheet, col);
            return result;
        }

当 mi form 初始化时,我这样做:

public partial class Form2 : Form
    {
        List<string> test_col = new List<string>();
        Python_Script my_py = new Python_Script("script_leer_excel.py");

        public Form2()
        {
            test_col =  my_py.Col_Values(0,0);
        }

这是我的python脚本

import sys
import xlrd

loc = ("excel_route")
wb = xlrd.open_workbook(loc)

def Col_Values(sheet, col):
    sheet = wb.sheet_by_index(sheet)
    result = sheet.col_values(col)
    return result

但是当我运行代码时出现错误: IronPython.Runtime.Exceptions.ImportException: 'No module named xlrd'

我不知道如何在 Ironpython 中安装 xlrd 模块,我使用 python 3.8 的命令 promt 安装了它,并且我在 Visual strudio 中的 python 环境告诉我我正在运行 python 3.8 Visual Studio python 环境

标签: pythonc#visual-studiowinformsironpython

解决方案


推荐阅读