Oracle UTL_FILE - Excel 中单个单元格的多行



我需要在csv文件中显示以下内容UTL_FILE该文件是使用PL/SQL包生成的。

标题

1 标题2 标题3ABCDE 123 987641213 三十街 年

对于"Heading1"中的每个值,我从特定表中获取 3 行地址。在输出 csv 文件中,我需要在单个单元格中显示地址,数据由新行分隔。

我尝试使用光标并使用 chr(10)、chr(12)、chr(15) 附加数据,但徒劳无功。

请帮助我获得输出。

你必须引用你的字段,该字段有回车

heading1,headiing2,heading3
abcde,123,"1 street
town
90210"
abcde,124,"13 street
town
43245"

DazzaL 建议的内容应该有效,但如果您无法更改输入文件,您可以使用以下代码:

declare
    v_line varchar2(2000);
    v_c1   varchar2(10);
    v_c2   varchar2(10);
    v_c3   varchar2(1980);
    nb_line_per_record integer := 3;
    v_line_in_record   integer;
    v_seperator varchar2(1) := ',';
    v_file UTL_FILE.FILE_TYPE;
begin
    v_file := utl_file.FOPEN(your_directory, 'your_file','r');
    v_line_in_record := 0;
    --we skip the first line
    UTL_FILE.GET_LINE(v_file, v_line);
    loop
        v_line_in_record := v_line_in_record + 1; 
        begin
            UTL_FILE.GET_LINE(v_file, v_line);
        EXCEPTION
            WHEN no_data_found THEN
                exit;
        END;
        --first line of record we cut by v_seperator
        if v_line_in_record = 1 then
           v_c1 := substr(v_line,1,instr(v_line,v_seperator,1,1)-1);
           v_c2 := substr(v_line,instr(v_line,v_seperator,1,1)+1,
                          instr(v_line,v_seperator,1,2)-                                
                          instr(v_line,v_seperator,1,1)-1);
           v_c3 := substr(v_line,instr(v_line,v_seperator,1,2)+1) 
                          || char(10);--if you want new line in adresse 
        else
            --not first line we concatanate to adress with new line
            v_c3 := v_c3 || v_line ||
                    case when v_line_in_record = 2 then char(10) else '' end; 
        end if;
        if v_line_in_record = 3 then
            v_line_in_record := 0;
            --do something with your record 
            insert into yourtable values (v_c1,v_c2,v_c3);
        end if;
    end loop;
    UTL_FILE.FCLOSE(v_file);
    COMMIT;
end;

但这只有在您绝对确定每条记录都是 3 行时才有效。如果我是你,我会在每条记录后添加一个记录分隔符,并使用 SQLLOADER 将此文件加载到表中。您可以使用 SQLLOADER 定义记录分隔符。这是一个示例 ctl 它使用 & 作为记录分隔符

options (skip=1) 
  load data 
  infile "yourfile" "str '&'" 
  truncate into table your_table 
  fields terminated by "," 
  trailing nullcols 
  (heading1, heading2, heading3)

如果您使用记录分隔符,您甚至可以在文件上创建外部表。

最新更新