雖然目前pl/sql developer等數據庫客戶端軟件都支持將表數據以excel格式導出,但是如果數據量大,需要等客戶端加載表數據等待很久。而且,可能會遇到定時以excel格式導出數據的要求。因此我自己寫了一個使用存儲過程將表數據以excel格式導出的存儲過程。
- 服務端新建目錄
create directory DIR_EXCEL as 'D:\DIR_EXCEL'; - 新建存儲過程
create or replace procedure pr_export_to_excel(p_table_name varchar2,
p_where_predicate varchar2 default null) is
/*
propose:根據表名和where條件生成excel
p_where_predicate:where條件語句
*/
out_file utl_file.file_type; --定義一個文件類型變量
str1 varchar2(20000); --定義一個字符串變量,用于存儲表1的字段名
str1_chr varchar2(30000);
l_sql varchar2(20000);
l_where_predicate varchar2(30000) default 'where ' || p_where_predicate;
begin
if p_where_predicate is null then
l_where_predicate := null;
end if;
--查詢表1的字段名,用制表符分隔,并賦值給str1
select listagg(column_name, chr(9)) within group(order by column_id)
into str1
from user_tab_columns
where table_name = upper(p_table_name);
--查詢表1的字段名,用制表符分隔,并賦值給str1_chr
select listagg(case
when t.DATA_TYPE = 'DATE' OR t.DATA_TYPE LIKE 'TIMESTAMP%' THEN
'to_char(f_cur.' || column_name || ',''YYYYMMDD HH24:MI:SS'')'
else
'f_cur.' || column_name
END,
'||chr(9)||') within group(order by column_id)
into str1_chr
from user_tab_columns t
where table_name = upper(p_table_name);
l_sql := '
declare
out_file utl_file.file_type; --定義一個文件類型變量
BEGIN
--打開一個文件,指定目錄對象、文件名和寫入模式
out_file := utl_file.fopen('' DIR_EXCEL '',
''' || p_table_name ||
'.xls '',
'' W '',
32767);
utl_file.put_line(out_file,
''' || str1 ||
'''); --寫入字段名,換行
for f_cur in (select *
from ' || p_table_name || ' t ' ||
l_where_predicate || ') loop
utl_file.put_line(out_file, ' || str1_chr || ');
end loop;
utl_file.fclose(out_file);
exception
when others then
utl_file.fclose(out_file); --關閉文件,防止異常關閉
dbms_output.put_line(SQLERRM);
dbms_output.put_line(dbms_utility.format_error_backtrace);
raise; --拋出異常信息
end;
';
dbms_output.put_line(l_sql);
--dbms_output.put_line(l_sql);
execute immediate l_sql;
exception
when others then
utl_file.fclose(out_file); --關閉文件,防止異常關閉
dbms_output.put_line(SQLERRM);
dbms_output.put_line(dbms_utility.format_error_backtrace);
raise; --拋出異常信息
end pr_export_to_excel;
3.調用存儲過程
call pr_export_to_excel('TEST','NAME='''123''');
4.去目錄'D:\DIR_EXCEL'取出TEST.xls文件
浙公網安備 33010602011771號