Wednesday, 2 July 2008

Creating CSV files the (well - an) easy way

Recently I've been asked to generate some GL extracts. Specifically:

  • A GL balance extract
  • An extract of the account segment values and descriptions
  • An extract of the hierarchies for the various account segments.
Now, whilst something like a hierarchy might seem an ideal candidate for expressing in XML format, my employer wants this generated the old fashioned .CSV way. I knocked up the below function which let's you generate your CSV data record as simply as:

v_file_line := csvize(t_stringlist('Contents of Field 1','Contents of "Field 2"',etc...));

You can specify as many fields as you like and the function deals appropriately with strings containing the quote character (by double quoting them - which seems to be pretty standard).

TYPE t_stringlist IS TABLE OF VARCHAR2(256);

-- Format a list of strings as CSV
----------------------------------
function csvize(p_stringlist t_stringlist) return varchar2 is
deliminator constant char(1) := '"';
separator constant char(1) := ',';
line VARCHAR2(1000);
begin
FOR i IN p_stringlist.FIRST .. p_stringlist.LAST LOOP
line := line || deliminator || REPLACE(p_stringlist(i),deliminator, deliminator || deliminator) || deliminator;
IF i != p_stringlist.LAST THEN
line := line || separator;
END IF;
END LOOP;
RETURN line;
end;

If you find it useful, let me know!

No comments: