Generating SLK Files from Oracle to Open in Excel

We will explore creating a package in Oracle PL/SQL, Paq_Sylk, designed to generate the contents of a Symbolic Link (SLK) file from a SELECT query and return it as a BLOB.

4/9/20255 min read

Icon for the article on generating SLK files from an Oracle database
Icon for the article on generating SLK files from an Oracle database

Generating SLK Files from Oracle to Open in Excel

A Robust Solution for Exporting Data to Excel

In enterprise application development, the need to export data from Oracle databases to versatile formats such as Microsoft Excel is a common task. While there are traditional methods, such as generating files directly in the server operating system, a powerful and flexible alternative is to generate the file contents directly in PL/SQL and deliver them as a BLOB (Binary Large Object) data type. In this article, we will explore the creation of an Oracle PL/SQL package, Paq_Sylk, designed to generate the contents of a Symbolic Link (SLK) file from a SELECT query and return it as a BLOB.

Why generate SLK content as BLOB from Oracle PL/SQL?

  • Flexibility in Delivery: Returning content as a BLOB offers great flexibility in how the file is delivered to the end user. The BLOB can be downloaded through a web application, stored in a table for further processing, sent as an email attachment, or transmitted through various channels.

  • File Server Independence: This strategy eliminates the need to write files to the Oracle server's file system, simplifying permissions management, increasing security, and avoiding concurrency issues.

  • Integration with Applications: Facilitates integration with modern applications that can efficiently consume and process BLOBs, such as web applications developed in Oracle APEX, Java, Python, etc.

What is an SLK file?

The SLK format is a text file format used for data exchange between spreadsheet applications, primarily Microsoft Excel. It is a simple, character-based format that organizes data into rows and columns.

Creating our PL/SQL Package: Paq_Sylk

The Paq_Sylk package encapsulates the logic for generating SLK content as a BLOB. Below, we'll break down its key components:

  • Custom Data Types: The package defines custom data types to improve code clarity and organization:

    • Cursor_Ref_Type is a reference cursor type used to process dynamic query results.

    • Array_Type is an integer-indexed VARCHAR2 table, which acts as an array to store the data for each row in the query.

    • Array_Type_Column_Type is another VARCHAR2 table that stores the data types of each column ('A' for alphanumeric, 'N' for numeric, 'F' for date).

    • F_Clob_To_Blob Function: This function converts a CLOB (Character Large Object) to a BLOB. This is an important utility because SLK content is initially constructed as text and then converted to a BLOB type for delivery. Use DBMS_LOB.Createtemporary to create a temporary BLOB. Read the CLOB in chunks using DBMS_LOB.Read and write the chunks to the BLOB using DBMS_LOB.Write. Handle the NO_DATA_FOUND exception to terminate the read loop.

  • Fun_Genera_Slk Function: This is the main function that generates the SLK content and returns it as a BLOB.

    • Declares local variables and cursors:

      • V_Slk_File (CLOB): Stores the contents of the SLK file while it is being built.

      • Cur_Process: Cursor that retrieves the SQL query (Query_Export) from the Tquery table based on the provided Process_Id.

      • Cur_Columns: Cursor that retrieves column information (name, data type) from the Tcolumns table for the given Process_Id.

      • V_Ref_Cursor: Dynamic reference cursor that is opened to execute the SQL query retrieved from the Tquery table.

    • Builds the SLK file header: Initializes the V_Slk_File variable with the initial lines required by the SLK format.

    • Generate column headers: Iterate through the Cur_Columnas cursor to obtain the column names.

    • Constructs the SLK lines that define the column headers ('F;SDM5;Y1;X', 'C;Y1;X', etc.).

    • Stores the column data types in the V_Data_Type array.

    • Executes the query and processes the results: Opens the dynamic reference cursor V_Ref_Cursor to execute the SQL query.

    • Traces the query results row by row. For each row, it iterates through the columns and generates the SLK lines corresponding to the data, taking into account the data type of each column (alphanumeric, numeric, or date).

    • Uses the P_Add_Line function to add lines to the CLOB V_Slk_File, handling the maximum line length.

    • Finalizes the SLK file and converts it to a BLOB:

    • Adds the final line 'E' to the SLK file. Call the F_Clob_To_Blob function to convert the V_Slk_File CLOB to a BLOB.

    • Return the resulting BLOB.

    • Exception Handling: Include an EXCEPTION block to catch any errors during processing and raise a custom exception with Raise_Application_Error.

Example of Use

To use the package, you first need to have the configuration tables (Tquery, Tcolumns) populated. The example script provides these tables and sample data:

  • Tproductos: Sample table with product data.

  • Tquery: Table that stores the SQL queries to be executed.

  • Tcolumnas: Table that defines the columns to be included in the SLK file and their data types.

Then, you can call the Paq_Sylk.Fun_Genera_Slk function to obtain the BLOB:


SQL

SELECT Paq_Sylk.Fun_Genera_Slk(1, 'Productos.slk') FROM DUAL;

This will execute the query stored in Tquery with Process_Id = 1, generate the SLK content, and return it as a BLOB. Opening the BLOB displays the file as follows:

Result of generating slk file from Oracle database
Result of generating slk file from Oracle database

How to consume BLOB SLK?

The BLOB returned by the Fun_Genera_Slk function can be consumed in several ways, depending on your needs:

  • Download via a web application (Oracle APEX, etc.): The application can retrieve the BLOB and configure it as a file download, setting the appropriate MIME type (application/x-slk or application/octet-stream).

  • Save to an Oracle table: The BLOB can be stored in a BLOB column in a table for later processing, auditing, or deferred downloading.

  • Additional processing in PL/SQL: Although less common, the BLOB can be manipulated within PL/SQL if necessary (e.g., to compress it before storing it).

  • Attach it to an email: If you have a process that sends emails, you can have a parameter to send an attachment and use the output from this packet.

Advantages of this Solution (with focus on BLOB)

  • Versatile Delivery: Delivering the SLK file as a BLOB allows for great flexibility in how users or applications consume the data.

  • Enhanced Security: By avoiding direct writes to the server's file system, security risks and permission issues are reduced.

  • Simplified Integration: The nature of the BLOB facilitates integration with web applications and other platforms that can efficiently handle binary data.

  • Logic Centralization: The PL/SQL package encapsulates all SLK file generation logic, facilitating code maintenance and reuse.

Additional Considerations

  • Performance: For large volumes of data, BLOB generation can consume significant memory and CPU resources. It is important to optimize SQL queries and consider paging data if necessary.

  • Error Handling: The package includes error handling, but it is crucial to implement appropriate error handling in the application consuming the BLOB to ensure system robustness.

  • Character Encoding: Ensuring the correct character encoding is essential to avoid problems when opening the SLK file in Excel. The provided package appears to handle this implicitly, but attention should be paid to the data encoding in the database.

  • SLK Format Limitations: The SLK format has some limitations compared to more modern formats such as XLSX. Consider whether SLK fully meets your formatting and data complexity needs.

  • Query Parameters: If you want the query to have parameters, you can enhance the process to allow this functionality. You can add parameters to the query using a convention like @@param1@@ and replace them with the desired values ​​at runtime, before processing the query.

  • Column limit: This example has a limit of 25 columns for the resulting file, but you can adapt it to your needs.

Conclusion

The Paq_Sylk package provides a robust and flexible solution for generating SLK content as BLOBs from Oracle PL/SQL. By encapsulating the generation logic and leveraging PL/SQL's capabilities for data manipulation and content generation, this approach simplifies data export to Excel and improves integration with other applications.

The Paq_sylk package script is provided below.