excel文件数据导入sqlote数据库实验报告编写程序,生成 50 个 Excel 文件,每个文件中包含 5 列数据,其中每个单元格内的内 容随机生成,并且每个 Excel 文件的数据行数不相同。然后创建一个 SQLite 数据库,其结 构与 Excel 文件相符合,最后把前面生成的 50 个 Excel 文件中的数据导入到这个数据库 中。
时间: 2024-02-17 12:01:03 浏览: 38
实验目的:
通过Python编写程序生成50个Excel文件,每个文件包含5列数据,然后使用pandas库将这些Excel文件中的数据导入到SQLite数据库中。
实验步骤:
1. 导入必要的Python库:pandas、sqlite3、random、string。
```
import pandas as pd
import sqlite3
import random
import string
```
2. 定义生成随机字符串的函数。
```
def random_string(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
```
3. 定义生成随机整数的函数。
```
def random_int(low, high):
return random.randint(low, high)
```
4. 生成50个Excel文件,并将每个文件中的数据随机生成。
```
for i in range(50):
# 生成文件名
filename = 'data_' + str(i) + '.xlsx'
# 生成数据行数
rows = random.randint(5, 20)
# 生成数据
data = []
for j in range(rows):
row = []
row.append(j + 1)
row.append(random_string(5))
row.append(random_int(1, 100))
row.append(random.choice(['male', 'female']))
row.append(random_string(10))
data.append(row)
# 将数据存储为DataFrame对象,并将数据写入Excel文件
df = pd.DataFrame(data, columns=['id', 'name', 'age', 'gender', 'description'])
df.to_excel(filename, index=False)
```
5. 连接SQLite数据库,创建数据表。
```
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''CREATE TABLE data
(id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
gender TEXT,
description TEXT);''')
conn.commit()
```
6. 遍历50个Excel文件,将每个文件中的数据导入到SQLite数据库中。
```
for i in range(50):
# 读取Excel文件中的数据
filename = 'data_' + str(i) + '.xlsx'
df = pd.read_excel(filename)
# 将数据插入到数据表中
df.to_sql('data', conn, if_exists='append', index=False)
```
7. 关闭数据库连接。
```
conn.close()
```
实验结果:
成功生成了50个Excel文件,并将每个文件中的数据导入到SQLite数据库中。
实验结论:
使用Python中的pandas库和sqlite3库可以轻松地实现Excel文件和SQLite数据库之间的数据导入和导出,大大提高了数据处理的效率和准确性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)