python將 獲取oracle數據存入excel
时间: 2023-09-15 12:20:57 浏览: 32
你可以使用Python中的cx_Oracle和openpyxl模块来完成这个任务。首先,你需要安装这些模块:
```pip install cx_Oracle openpyxl```
接下来,你可以按照以下步骤编写Python代码:
1. 导入必要的模块
```python
import cx_Oracle
from openpyxl import Workbook
```
2. 创建一个Oracle数据库连接
```python
dsn_tns = cx_Oracle.makedsn('hostname', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
```
3. 准备SQL查询语句并执行它
```python
cursor = conn.cursor()
query = "SELECT column1, column2, column3 FROM table_name"
cursor.execute(query)
```
4. 将查询结果存储在一个Excel文件中
```python
wb = Workbook()
ws = wb.active
ws.append(['Column 1', 'Column 2', 'Column 3'])
for row in cursor:
ws.append(row)
wb.save('output.xlsx')
```
完整的Python代码如下所示:
```python
import cx_Oracle
from openpyxl import Workbook
# 创建Oracle数据库连接
dsn_tns = cx_Oracle.makedsn('hostname', 'port', service_name='service_name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
# 执行SQL查询语句
cursor = conn.cursor()
query = "SELECT column1, column2, column3 FROM table_name"
cursor.execute(query)
# 将查询结果存储在Excel文件中
wb = Workbook()
ws = wb.active
ws.append(['Column 1', 'Column 2', 'Column 3'])
for row in cursor:
ws.append(row)
wb.save('output.xlsx')
# 关闭数据库连接
cursor.close()
conn.close()
```
在上面的代码中,你需要将“hostname”,“port”,“service_name”,“username”,“password”和“table_name”替换为你自己的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)