Oracle存儲過程將執行結果導出生成Excel文件

---directories新建存儲路徑
create or replace directory DIR_EXCEL as '/opt/leasing';
 
create or replace procedure PRC_TASK_EXCEL is
 
out_file utl_file.file_type; --定義一個文件類型
 
L_FILENAME varchar2(200);
 
str1 varchar2(200);
 
str2 varchar2(200);
 
begin
 
--定義Excel文件名稱
 
select to_char(sysdate, 'yyyymmddhh24miss') || '.xls'
 
into L_FILENAME
 
from dual;
 
--定義Excel文件擡頭
 
select '姓名' into str1 from dual;
 
select '電話' into str2 from dual;
 
--導出Excel文件
 
out_file := utl_file.fopen('DIR_EXCEL', L_FILENAME, 'W');
 
--寫入Excel擡頭內容
 
utl_file.put(out_file, convert(str1, 'ZHS16GBK'));----根據Oracle數據庫的字符編碼進行轉換
 
utl_file.put(out_file, convert(str2, 'ZHS16GBK'));
 
utl_file.put_line(out_file, '');
 
--循環寫入Excel明細
 
for o in (select c.bakhxm || chr(9) xm, c.bakhzh || chr(9) zh
 
from bat001 c) loop
 
utl_file.put(out_file, convert(o.xm, 'ZHS16GBK'));
 
utl_file.put(out_file, convert(o.zh, 'ZHS16GBK'));
 
utl_file.put_line(out_file, '');
 
end loop;
 
utl_file.fflush(out_file);
 
utl_file.fclose(out_file); --關閉文件流
 
--處理異常
 
exception
 
when others then
 
rollback;
 
utl_file.fclose(out_file); --關閉文件流,防止異常關閉
 
end PRC_TASK_EXCEL;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章