[Python] Using Python in Excel and trying to insert value from Python into cell

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    The question from PythonProgramming came closest to my question but the answer was unsatisfactory. There is very little documentation on Python-In-Excel. I am running a Python script INSIDE Excel which contains a loop and I would like to "print" the number of iterations (number_of_points) to a cell in the same sheet. Most of the documentation pertains to large databases which I am not interested in. I create science and math worksheets using Excel and Python, and previously, VBA. Here is the script:

    import numpy as np
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize=(10,10))
    ax = fig.add_subplot(1, 1, 1)

    a = xl("F2")
    b = xl("G2")
    c = xl("H2")
    d = xl("I2")
    x = np.linspace(-10, 10, 400)
    y1 = -a*x+b
    y2 = 0*x+c

    # Create the plot


    plt.plot(x, y1, color='blue', ls='--')
    plt.plot(x, y2, color='red', ls='--')
    plt.axvline(x = d, color = 'g', ls = "--")

    number_of_points = 0
    for i in range(-10, 11):
    for j in range(-10, 11):
    if a*i + j < b and j > c and i > d:
    plt.plot(i, j, 'go') # 'go' for green points
    number_of_points = number_of_points + 1


    # Major ticks every 20, minor ticks every 5
    major_ticks = np.arange(-10, 11, 1)
    minor_ticks = np.arange(-10, 11, 1)

    ax.set_xticks(major_ticks)
    ax.set_xticks(minor_ticks, minor=True)
    ax.set_yticks(major_ticks)
    ax.set_yticks(minor_ticks, minor=True)
    ax.axhline(linewidth=1.2, color="k")
    ax.axvline(linewidth=1.2, color="k")
    # And a corresponding grid
    ax.grid(which='both')

    # Or if you want different settings for the grids:
    ax.grid(which='minor', alpha=0.2)
    ax.grid(which='major', color ="black", linewidth = 0.6, alpha=0.8)
    plt.xlim(-10, 10)
    plt.ylim(-10, 10)
    plt.show()


    Currently, the code produces a graph which I want. Just need the number_of_points returned too. One number, not a database. Below is a picture of the graph produced by the script.

    [​IMG]

    Continue reading...

Compartilhe esta Página