How to use Aspose.Cells for Python via Java in Gunicorn+Flask environment

Complete environment preparation

The example running environment of this guide is Ubuntu: 20.04, you can adjust it according to your actual situation. In order to ensure that the examples can run properly, we need to install some necessary tools in the environment. The following is a brief step-by-step guide to help you complete the process. Please note that this is only a rough guide, and the specific details may vary depending on your system and needs.

Python

If not installed, install it as follows:

sudo apt install python3 python3-pip # Ubuntu/Debian
#sudo yum install python3 python3-pip # CentOS/RHEL

Check version

python3 --version
pip3 --version

Java

If not installed, install it as follows:

sudo apt install openjdk-11-jdk # Ubuntu/Debian
#sudo yum install java-17-openjdk # CentOS/RHEL
ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
ENV PATH=$JAVA_HOME/bin:$PATH

Check version

java -version

virtualenv virtual environment

The virtual environment is installed based on your actual needs. It is recommended to use virtual environments to manage project dependencies in both development and production environments. Please follow the following command to install:

sudo apt install python3-venv # Ubuntu/Debian
#sudo yum install python3-venv # CentOS/RHEL

Create a virtual environment

python3 -m venv myenv # Create a virtual environment named myenv in the current directory

Start the virtual environment

source myenv/bin/activate

Notice: If a virtual environment is used, the following operations require the activation of the corresponding virtual environment first

Flask

If not installed, please follow the following command to install:

pip install Flask

Gunicorn

If not installed, please follow the following command to install:

pip install gunicorn

Jpype

If not installed, please follow the following command to install:

pip install jpype1

aspose-cells

If not installed, please follow the following command to install:

pip install aspose-cells

Creating the Hello World Application

To create the Hello World application using Aspose.Cells API:

  1. Create an instance of the Workbook class.
  2. Apply the license:
    1. If you have purchased a license, then use the license in your application to get access to Aspose.Cells' full functionality
    2. If you are using the evaluation version of the component (if you’re using Aspose.Cells without a license), skip this step.
  3. Create a new Microsoft Excel file, or open an existing file in which you want to add/update some text.
  4. Access any cell of a worksheet in the Microsoft Excel file.
  5. Insert the words Hello World! into a cell accessed.
  6. Generate the modified Microsoft Excel file.

The examples below demonstrate the above steps.

Creating a Workbook

The following example creates a new workbook from scratch, writes the words “Hello World!” into cell A1 on the first worksheet, and saves the file.

Suppose we have a test path “/app”. We will complete the following work under this test path.

Flask application files: hello.py

from flask import Flask, request, jsonify
import threading
# Creating a Flask Application
def create_app():
print("Start create_app")
app = Flask(__name__)
@app.route("/")
def home():
# Returns HTML page content
return """
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Python via Java in Flask</title>
</head>
<body>
<h1>Welcome to Aspose.Cells Python via Java</h1>
<p>This is an example of how to use Aspose.Cells Python via Java in Flask.</p>
<p>This example creates a new workbook object and enters "Hello World" in the specified cell, and finally saves it with the file name you specify.</p>
<pre><code>
import jpype
import asposecells
if not jpype.isJVMStarted():
jpype.startJVM()
from asposecells.api import Workbook, CellsHelper
workbook = Workbook()
workbook.getWorksheets().get(0).getCells().get("A1").putValue("Hello World")
workbook.save("NameYouSpecified" + ".xlsx")
</code></pre>
<label>Enter Your File Name:</label>
<input type="text" id="name" name="name" required>
<button id="btn_save">Generate</button>
<p id="message"></p>
<script>
//Bind a click event to button Save
document.getElementById("btn_save").addEventListener("click", function() {
var name = document.getElementById('name').value;
fetch("/button_save?name=" + encodeURIComponent(name))
.then(response => response.json())
.then(data => {
document.getElementById("message").innerText = "The generated file is saved as " + data.FileName + ".xlsx";
});
});
</script>
</body>
</html>
"""
@app.route("/button_save", methods=["GET"])
def increment_button1():
"""Handle the click event of button Save"""
import jpype
import asposecells
if not jpype.isJVMStarted():
jpype.startJVM()
from asposecells.api import Workbook, CellsHelper
#print("Version: " + CellsHelper.getVersion())
workbook = Workbook()
workbook.getWorksheets().get(0).getCells().get("A1").putValue("Hello World")
name = request.args.get('name')
workbook.save(str(name) + ".xlsx")
return jsonify({"message": "Button Save clicked", "FileName": str(name)})
return app

Custom Gunicorn startup class file: custom_gunicorn.py

from gunicorn.app.base import BaseApplication
from hello import create_app
class CustomGunicornApplication(BaseApplication):
"""
Customizing the Gunicorn Startup Class
"""
def __init__(self, app, options=None):
self.app = app
self.options = options or {}
super().__init__()
def load_config(self):
"""Loading Gunicorn’s configuration"""
for key, value in self.options.items():
self.cfg.set(key.lower(), value)
def load(self):
"""Loading the Flask application"""
return self.app
def on_starting(self, server):
"""Fired when the Gunicorn main process starts"""
print("Gunicorn is starting... Running some initialization tasks...")
self.initialize_system()
def initialize_system(self):
"""Perform certain tasks at startup, such as logging or loading resources"""
print("System initialized!")
if __name__ == "__main__":
# Creating a Flask Application
app = create_app()
# Gunicorn Configuration
gunicorn_options = {
"bind": "0.0.0.0:5000", # Bind address and port
"workers": 2, # Number of worker processes
"loglevel": "info", # Log level
}
# Starting a custom Gunicorn application
CustomGunicornApplication(app, gunicorn_options).run()

Start the service

Verify that all packages required by the service are installed, then start the service.

If you use the python3-venv virtual environment, you need to create a virtual environment in the test path, start it, and then install all the required tool packages.

python custom_gunicorn.py Or python3 custom_gunicorn.py

Check results

1 Open the browser and visit http://127.0.0.1:5000/.

2 Enter the file name you want to save in the input box.

3 Click the ‘Generate’ button to save the file.

After doing this, you will get an Excel file named after the content you entered in the current test path. The preview effect is as follows:

todo:image_alt_text

Using Docker

Or you can put the above operations into a docker container. It is very simple to use Docker to build the environment used by the example. Just put the above operations into the Dockerfile file.

Here is a Dockerfile file for reference. It lists some necessary toolkits required to build the environment.

Dockerfile

FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
    python3 \
    python3-pip \
    python3-dev \
    python3-venv \
    build-essential \
    libssl-dev \
    libffi-dev \
    libpq-dev \
    openjdk-11-jdk \
    wget \
    curl \
    unzip \
    && rm -rf /var/lib/apt/lists/*
ENV JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
ENV PATH=$JAVA_HOME/bin:$PATH
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
CMD ["python3", "custom_gunicorn.py"]

requirements.txt

This file is mainly used to provide a dependency environment for Python projects. You can modify the version in this file to suit your needs.

aspose-cells==24.11.0
jpype1==1.5.1
Flask==3.0.3
gunicorn==23.0.0

Main files

The main file structure is as follows:

app/
|-requirements.txt
|-hello.py
|-custom_gunicorn.py

Start the container

You can start the container using the following command

docker run --rm -p 127.0.0.1:5000:5000 gunicorn_flask:v1.0 # gunicorn_flask:v1.0 - Image built by Dockerfile