Output the specified table of Oracle database in Python to Excel for each file

Reason for making

I am making an Oracle web application, but I made it to easily output data for confirmation and backup.

Prerequisites

OS:Windows 8.1 Python:2.7.10 x64 Required modules: cx_Oracle, xlwt

code

output_oracle_to_excel.py


# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import os,sys
import csv
import codecs
import numbers
import unittest
import cStringIO
import itertools

import cx_Oracle

import xlwt

from itertools import chain

os.environ["NLS_LANG"] = "JAPANESE_JAPAN.AL32UTF8"

ORACLE_CONF = {
	'ID'		: 'SCHEMENAME'
	, 'PASS'	: 'SCHEMEPASSWORD'
	, 'HOST'	: '192.168.1.5'
	, 'SID'		: 'XE'
}

def fetchTables( table_name ):
	output_file_name = 'DB_to_Excel_' + HOST + '_' + ID + '_' + table_name + '.xls'

	wb = xlwt.Workbook()				#Create a new workbook
	ws = wb.add_sheet( table_name )		#Create a new worksheet

	column_name_sql = 'select column_name from user_tab_columns where table_name = :tbl'
	cur_columns = conn.cursor()
	cur_columns.execute(column_name_sql, tbl=table_name)
	columns = cur_columns.fetchall()
	cur_columns.close()
	columns = tuple(chain.from_iterable(columns))

	data_sql = 'select * from "%s"' % table_name
	cur_data = conn.cursor()
	cur_data.execute(data_sql)

	nRow = 0
	nLine = 0
	for value in columns:
		ws.write(nRow, nLine, value) 
		nLine = nLine + 1

	row = cur_data.fetchone()

	nRow	= 1
	while row != None:										#If you have the data
		nLine = 0
		for value in row:									#Get element loop
			if isinstance( value , cx_Oracle.LOB ):
				value = value.read()
			ws.write(nRow, nLine, value)					#Write to excel
			nLine = nLine + 1
		nRow = nRow + 1
		row = cur_data.fetchone()							#To the next record

	cur_data.close()
	wb.save( output_file_name )							#Save Excel file


def fetchAllTables( conn ):
	str_sql = "select TABLE_NAME from user_tables where TABLE_NAME LIKE '%USER%' or TABLE_NAME LIKE '%SHOP%' ORDER BY TABLE_NAME"
	cur_tables = conn.cursor()
	cur_tables.execute( str_sql )
	rows = cur_tables.fetchall()
	i = 0
	lst_table = list()
	for row in rows:
		print row[0]
		lst_table.append( row[0] )
		fetchTables(lst_table[i])
		i = i + 1

conn = cx_Oracle.connect( ORACLE_CONF['ID'] , ORACLE_CONF['PASS'] , ORACLE_CONF['HOST'] + '/' + ORACLE_CONF['SID'] )

fetchAllTables( conn )

Commentary

Oracle character code

os.environ["NLS_LANG"] = "JAPANESE_JAPAN.AL32UTF8" It is specified by. Recently, UTF-8 has increased, so I think that UTF-8 can be used as it is.

Connection information

ORACLE_CONF = { 'ID' : 'SCHEMENAME' , 'PASS' : 'SCHEMEPASSWORD' , 'HOST' : '192.168.1.5' , 'SID' : 'XE' } Please change according to your own environment as appropriate

Output file name

def fetchTables( table_name ): output_file_name = 'DB_to_Excel_' + HOST + '' + ID + '' + table_name + '.xls'

The file name is generated in the part of. For example, if the table acquired with HOST: 192.168.1.5 and ID: SCHEMENAME is "TEST_USER", DB_to_Excel_192.168.1.5_SCHEMENAME_TEST_USER.xls The output result is saved in the file.

When narrowing down the output table or not narrowing down

def fetchAllTables( conn ): str_sql = "select TABLE_NAME from user_tables where TABLE_NAME LIKE '%USER%' or TABLE_NAME LIKE '%SHOP%' ORDER BY TABLE_NAME" It is possible if you change the WHERE clause of.

Recommended Posts

Output the specified table of Oracle database in Python to Excel for each file
Change the standard output destination to a file in Python
[Python] How to output a pandas table to an excel file
Google search for the last line of the file in Python
Convert Excel file to text in Python for diff purposes
Python> library> os> os.walk ()> Get directory structure / Implementation to get each file path in the specified directory
How to set the output resolution for each keyframe in Blender
Output the contents of ~ .xlsx in the folder to HTML with Python
[Python] Read the specified line in the file
Test & Debug Tips: Create a file of the specified size in Python
Open an Excel file in Python and color the map of Japan
Python script that outputs all records of Oracle table to CSV file
Switch the module to be loaded for each execution environment in Python
I made a program to check the size of a file in Python
Output the number of CPU cores in Python
Match the distribution of each group in Python
Output in the form of a python array
Speed evaluation of CSV file output in Python
Bad post for using "animeface-2009" in Python & Implementation of function to output to PASCAL VOC format XML file
Various ways to read the last line of a csv file in Python
[Bash] While read, pass the contents of the file to variables for each column
Compare the sum of each element in two lists with the specified value in Python
I created a script to check if English is entered in the specified position of the JSON file in Python.
Template of python script to read the contents of the file
How to get the number of digits in Python
[python] option to turn off the output of click.progressbar
[Python] How to output the list values in order
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Use Pandas to write only the specified lines of the data frame to an excel file
How to count the number of occurrences of each element in the list in Python with weight
Check the processing time and the number of calls for each process in python (cProfile)
It is easy to execute SQL with Python and output the result in Excel
Output "Draw ferns programmatically" to the drawing process in Python
Make a table of multiplication of each element in a spreadsheet (Python)
Manipulate the clipboard in Python and paste the table into Excel
Get the number of occurrences for each element in the list
[Python] How to change EXCEL file saved in xlsb to xlsx
Get the index of each element of the confusion matrix in Python
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
I tried to create a Python script to get the value of a cell in Microsoft Excel
How to find the cumulative sum / sum for each group using DataFrame in Spark [Python version]
Output the key list included in S3 Bucket to a file
How to determine the existence of a selenium element in Python
How to change the log level of Azure SDK for Python
Wrap (part of) the AtCoder Library in Cython for use in Python
How to know the internal structure of an object in Python
Save the binary file in Python
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
How to check the memory size of a variable in Python
Output to csv file with Python
Automatically resize screenshots for the App Store for each screen in Python
Put the process to sleep for a certain period of time (seconds) or more in Python
I want to output the beginning of the next month with Python
Read the standard output of a subprocess line by line in Python
Feel free to change the label of the legend in Seaborn in python
I wrote the code to write the code of Brainf * ck in python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
How to output the output result of the Linux man command to a file
I tried to summarize the contents of each package saved by Python pip in one line