最近做的一个项目,其中有一块的功能是将数据导出为excel文件。我使用了oracle的utl_file程序包。
主要实现思路:
1、声明一个纪录,用来存储导出的数据;
2、使用游标取数据到纪录中;
3、使用utl_file将纪录中的数据写入excel文件;
4、循环执行步骤2和3,完成数据的导出。
做的过程中主要遇到的问题:
1、excle文件中写数据如何写入下一列;
使用tab字符完成excel中横向跳格,excel中tab字符表示单元格的结尾,其中使用了chr()函数,
应用举例如下:
select u.user_name||chr(9),u.account||chr(9) from user u
例句1
例句1作为游标的主体,取出的数据每项都包含一个tab字符,使用utl_file.put()往excel文件中
写数据时会自动跳格
2、声明的纪录中各项的类型问题
这个问题的产生主要是在类型的强转化时产生。如例句1种的u.account为number型时,
添加||chr(9)时oracle会对进行强转化;当然这里的转化不会有问题(number转化为varchar2),
但是当这种强转换还是会出现问题的,如声明的纪录里某个属性声明为用户自己定义的一种类型,
oracle无法进行转换,则会报错。解决的办法很简单,可以将纪录的属性都声明为varchar类型,但是要注意长度。
3、导出文件存储路径问题
utl_file在写文件时,文件的存储路径必须在oracle初始化参数utl_file_dir中设置,
需重起服务才能生效。后来经过查资料发现可以先建立一个directory,在存储过程中使用它。
建立directory的语句:
create or replace directory filepath as path “;
例句2(注:path为存储文件的路径,如c:\temp)
以下是我简单做的处理hr.jobs表数据的存储过程:
create or replace procedure sp_jobs_data_out(
p_file_name in varchar2 –***处理文件名称,需包含扩展名(xls用于写excel文件)***–
) as
–***定义并声明存储交通资产信息的纪录***–
–***record_define start***–
type job_record_type is record(
job_id hr.jobs.job_id%type,
job_title hr.jobs.job_title%type,
min_salary varchar2(30)
);
job_rec job_record_type;
–***record_define end***–
–***定义获取job信息的游标***–
–***cursor_define start***–
cursor c_jobs is
select
job_id||chr(9), –***chr(9)是tab字符,保证数据输出到excel时能自动换到下一列***–
job_title||chr(9),
min_salary||chr(9)
from
hr.jobs;
–***cursor_define end***–
l_file utl_file.file_type; –***处理文件操作的句柄***–
begin
l_file :=utl_file.fopen(filepath,p_file_name,w); –filepath是先于导出前用户建立的存储导出文件的路径
utl_file.put_line(l_file,jobs表导出数据);
open c_jobs;
loop
fetch c_jobs into
job_rec.job_id ,
job_rec.job_title ,
job_rec.min_salary ;
exit when c_jobs%notfound;
utl_file.put(l_file,job_rec.job_id ); –***数据写入excle文件中***–
utl_file.put(l_file,job_rec.job_title);
utl_file.put_line(l_file,job_rec.min_salary);
end loop;
close c_jobs;
utl_file.fflush(l_file);
utl_file.fclose(l_file);
exception
when others then
if utl_file.is_open(l_file) then
utl_file.fclose(l_file);
end if;
end;
例句3(注:我的oracle版本为9.2)
这是我第一个blog,可能内容不是很有技术含量的说,但总希望记录一下自己的历程,分享大家的经验。
msn:lintaowen@hotmail.com