Table of Contents
Database->Excel
Why use SQLAlchemy?
The specific usage is as follows:
The first line of code is to first create a connection to the database.
Excel->Database
Import data from the database to excel:
Import data from excel to the database:
Home Backend Development Python Tutorial How to use three lines of Python code to import and export database and Excel?

How to use three lines of Python code to import and export database and Excel?

Apr 25, 2023 pm 08:01 PM
excel python database

How to use three lines of Python code to import and export database and Excel?

Database->Excel

How to use three lines of Python code to import and export database and Excel?

Let’s first take a look at the department table in the database. There are six pieces of data in this table, representing different departments.

Next, take a look at this Python code. First, import the library you need to use, SQLAlchemy, which is the most famous ORM tool in Python.

The full name is Object Relational Mapping.

Why use SQLAlchemy?

It abstracts your code from the underlying database and its associated SQL features.

The characteristic is to manipulate Python objects instead of SQL queries, that is, objects are considered at the code level instead of SQL. It embodies a kind of programmatic thinking, which makes Python programs more concise and easy to read.

The specific usage is as follows:

from sqlalchemy import create_engine
import pandas as pd
# 创建数据库连接
engine = create_engine('mysql+pymysql://root:211314@localhost/hong')
# 读取mysql数据
db = pd.read_sql(sql='select * from hong.department', con=engine)
# 导出数据到excel
db.to_excel('部门数据.xlsx')
Copy after login

The first line of code is to first create a connection to the database.

My mysql username is root and the password is 211314.

Because I am starting the local database service here, it is localhost.

The slash is followed by the name of the database hong

The second line of code is to use pandas's read_sql() to query the data in the mysql table department

The second line The code is to write the queried data to the local through to_excel() of pandas

The execution result is successfully written to the local excel file

How to use three lines of Python code to import and export database and Excel?

Excel->Database

Next let’s look at how to write local xlsx data into a mysql file.

from sqlalchemy import create_engine
import pandas as pd
# 创建数据库连接
engine = create_engine('mysql+pymysql://root:211314@localhost/hong')
# 读取xlsx文件
df = pd.read_excel('模拟数据.xlsx')
# 导入到mysql数据库
df.to_sql(name='test_data', con=engine, index=False, if_exists='replace')
Copy after login

The same first line of code is to first create a connection to the database

The second line of code uses pandas's read_excel() to read the local file. As follows:

This is one hundred pieces of data that I simulated using python’s faker

How to use three lines of Python code to import and export database and Excel?

The third step uses the to_sql() method of pandas to read The obtained data is written into mysql

After the code execution is completed, I return to my hong database in mysql and find that there is an extra table of test_data.

Open it and take a look. Then this data is the same as the local data.

so. Here we use three lines of code to import data from the database to excel, and another three lines of code to import data from excel to the database.

To summarize:

Two-way data import can be achieved with only 3 lines of code.

Import data from the database to excel:

1. Use sqlalchemy to create a database connection

2. Use pandas’ read_sql to read the database data

3 , Use pandas' to_csv to store data into a csv file

Import data from excel to the database:

1. Use sqlalchemy to create a database connection

2. Use pandas' read_csv to read Get the csv data

3. Use pandas’ to_sql to store the data into the database a

The above is the detailed content of How to use three lines of Python code to import and export database and Excel?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

See all articles