Export Data From Mysql to Excel Sheet Using Python
Last Updated :
30 Apr, 2024
We are given a MySQL database and our task is to export the data into an excel sheet using Python. In this article, we will see how to export data from MySQL to Excel Sheets using Python.
Export Data From Mysql to Excel Sheet Using Python
Below are some of the ways by which we can export data from MySQL to an Excel sheet using Python:
Export Data From Mysql to Excel Sheet Using Pandas Library
Pandas is a Python-based powerful manipulation tool that can be used for reading/importing data from different sources such as MySQL Database into Excel files. In this example, the below code imports Pandas and PyMySQL to connect to a MySQL database executes a query to retrieve data from a table, loads it into a DataFrame, exports it to an Excel file named 'output.xlsx', and closes the database connection.
Python3
import pandas as pd
import pymysql
connection = pymysql.connect(host='localhost',
user='username',
password='password',
database='database_name')
query = "SELECT * FROM table_name"
data = pd.read_sql(query, connection)
connection.close()
data.to_excel('output.xlsx', index=False)
Example:
Let's create a table in MySQL called python_connector_tb. The following queries will be used to do so:
CREATE TABLE python_connector_tb (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
email VARCHAR(100)
);
INSERT INTO python_connector_tb (name, age, email) VALUES
('John Doe', 30, '[email protected]'),
('Jane Smith', 25, '[email protected]'),
('Bob Johnson', 40, '[email protected]');
Output:
Mysql tableNow, we will use above code to export this into Excel sheet.
output.xlsxExport Data From Mysql to Excel Sheet Using Openpyxl Library
In this example, below code imports PyMySQL and openpyxl libraries to interact with MySQL databases and Excel files, respectively. It establishes a connection to a MySQL database, creates a new Excel workbook, executes an SQL query to fetch data from a table, and writes the fetched data to the Excel workbook.
Python3
import pymysql
from openpyxl import Workbook
# Connect to MySQL database
connection = pymysql.connect(host='localhost',
user='username',
password='password',
database='database_name')
# Create a new Excel workbook
wb = Workbook()
ws = wb.active
# Execute SQL query and fetch data
query = "SELECT * FROM table_name"
cursor = connection.cursor()
cursor.execute(query)
data = cursor.fetchall()
# Write data to Excel
for row_index, row_data in enumerate(data, start=1):
for col_index, cell_data in enumerate(row_data, start=1):
ws.cell(row=row_index, column=col_index, value=cell_data)
wb.save('output.xlsx')
# Close the connection
connection.close()
Example:
Let's create a table in MySQL called python_connector_tb. The following queries will be used to do so:
CREATE TABLE python_connector_tb (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
email VARCHAR(100)
);
INSERT INTO python_connector_tb (name, age, email) VALUES
('John Doe', 30, '[email protected]'),
('Jane Smith', 25, '[email protected]'),
('Bob Johnson', 40, '[email protected]');
Output:
SQL tableNow, we will use above code to export this into Excel sheet.
output.xlsx
Similar Reads
Export WhatsApp Chat History to Excel Using Python
In this article, we will discuss how to export a specific user's chats to an Excel sheet. To export the chats, we will use several Python modules and libraries. In the Excel file, we will create four columns: Date, Time, Name, and Message. We'll create these columns through Pandas, export all the ch
5 min read
Deleting Element from Table in MySql using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-
2 min read
How to extract date from Excel file using Pandas?
Prerequisite: Regular Expressions in Python In this article, Let's see how to extract date from the Excel file. Suppose our Excel file looks like below given image then we have to extract the date from the string and store it into a new Dataframe column. For viewing the Excel file Click Here. Approa
3 min read
Writing to an excel sheet using Python
Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work. Let's see how
2 min read
How to Copy a Table in MySQL Using Python?
In this article, we will create a table in MySQL and will create a copy of that table using Python. We will copy the entire table, including all the columns and the definition of the columns, as well as all rows of data in the table. To connect to MySQL database using python, we need PyMySql module.
3 min read
How to Show All Tables in MySQL using Python?
A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. In order to make python interact with
1 min read
How to store XML data into a MySQL database using Python?
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It i
3 min read
How to import an excel file into Python using Pandas?
It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a '.xlsx' format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an
2 min read
How to Get the Size of a Table in MySQL using Python?
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-
2 min read
Add comment to column in MySQL using Python
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a
3 min read