oracle中导出excel


create or replace directory MY_DIR
  as 'c:/abc';


create or replace procedure export_data_out_excel

/**
  使用utl_file将需要导出的数据写入到文本文件
  pfile_name:输出文件名。
  pexport_sql:执行的sql语句,select id||chr(9),name||chr(9) from tablename,chr(9)是TAB字符,以保证数据输出到excel能自动换到下一列。
  **/
as
  type som_content_record_type is record(
    car_num varchar2(250),
    cap_date varchar2(250),
    dev_chnname  varchar2(250),
    dev_chnid  varchar2(250));


  som_content_rec som_content_record_type;
  err_num         number;
  err_msg         varchar2(2000);

  type cur_som_content is ref cursor;

  c_som_content cur_som_content;
  l_file        utl_file.file_type;
begin
  l_file := utl_file.fopen('MY_DIR',to_char (sysdate-1, 'YYYY-mm-dd')|| '.xls', 'w');
  utl_file.put(l_file, '车牌号'||chr(9));
  utl_file.put(l_file, '抓拍时间'||chr(9));
  utl_file.put(l_file, '通道名称'||chr(9));
  utl_file.put_line(l_file, '通道编号'||chr(9));
  open c_som_content for 'select car_num||chr(9),to_char (cap_date, ''YYYY-mm-dd'')||chr(9),dev_chnname||chr(9),dev_chnid ||chr(9) from c_table t where t.cap_date >= to_date(to_char(sysdate, ''YYYY-mm-dd''), ''YYYY-mm-dd'') - 1 and t.cap_date <= to_date(to_char(sysdate,''YYYY-mm-dd''),''YYYY-mm-dd'')';
  loop
    fetch c_som_content
      into som_content_rec.car_num, som_content_rec.cap_date,som_content_rec.dev_chnname,som_content_rec.dev_chnid;

    exit when c_som_content%notfound;
    utl_file.put(l_file, som_content_rec.car_num);
    utl_file.put(l_file, som_content_rec.cap_date);
    utl_file.put(l_file, som_content_rec.dev_chnname);
    utl_file.put_line(l_file, som_content_rec.dev_chnid);
  end loop;

  close c_som_content;

  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);
      err_num := sqlcode;
      err_msg := substr(sqlerrm, 1, 2000);

      commit;
    end if;
end;

如果写:frw:=utl_file.fopen('c:\abc','emp.txt','w');

会报错
ora-29280  目录无效
改成
frw:=utl_file.fopen('MY_DIR','emp.txt','w');

猜你喜欢

转载自shizhijian870525.iteye.com/blog/1838886