Many times, when working with files and remote servers, it would be helpful if we could use code to manipulate directories and files to make processes more efficient.
In many organizations, Microsoft Excel files store data for different processes, and from time to time, we need to update the data stored in these files.
Having to update these files manually can be a nightmare. Adding to that, if you are working with remote servers, there will most likely need to be some copying back and forth to your local computer.
With Python, we can write a program that does these manipulations for us, and save a lot of headache.
Using Paramiko and Pandas, we can easily write xlsx files to a remote server.
How to Output an XLSX File to Remote Server Using Pandas, Paramiko and FTP
Below is the code that I use to output xlsx files to a remote server using Pandas and Paramiko.
First, we connect to the server. We can read from existing Excel files, or create our own. Then, we write back the Dataframe contents to the remote server in a XLSX file.
import io import paramiko import pandas as pd #connect to remote server host = "yourhost" username = "yourusername" password = "yourpassword" con = paramiko.SSHClient() con.load_system_host_keys() ftp.set_missing_host_key_policy(paramiko.AutoAddPolicy()) con.connect(host, username, password) ftp = con.open_sftp() #read in existing xlsx file contents to dataframe existing_xlsx = ftp.open("yourfilepath/existingfilename.xlsx") df = pd.read_excel(existing_xlsx) #xlsx manipulations here #output xlsx file back to remote server output = io.BytesIO() writer = pd.ExcelWriter(output, engine='openpyxl') df.to_excel(writer, sheet_name="Sheet1", index=False) writer.save() xlsx_data = output.getvalue() with ftp.open('yourfilepath/yourfilename.xlsx', "w", bufsize=32768) as f: f.write(xlsx_data)
Hopefully, this post has helped you with automating a process using Python and manipulating Microsoft Excel files on your remote server.
Can you do the opposite? Bringing an xlsx from a remote server using the same packages?
Yes, this is quite easy as it is just using the same Paramiko and then reading it in – instead of writing it out.
Here’s our post to help you do this: http://theprogrammingexpert.com/read-xlsx-file-from-remote-server-using-paramiko-ftp-pandas/