Creating an Excel file in COBOL directly requires generating a format that Excel can understand. One straightforward method is to write the data to a CSV file, which Excel can easily open as a spreadsheet. If you need a more complex Excel file with native features, it usually involves interacting with libraries or external tools, which aren't typically handled directly in COBOL. Here, we'll focus on generating a CSV file as that's easily manageable using standard COBOL file operations.
COBOL Program to Write CSV File
Here's a COBOL program that writes student mark data to a CSV file, which can be opened in Excel:
IDENTIFICATION DIVISION.
PROGRAM-ID. CreateCSV.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OUTPUT-FILE ASSIGN TO 'students.csv'
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD OUTPUT-FILE.
01 OUTPUT-RECORD PIC X(200).
WORKING-STORAGE SECTION.
01 STUDENTS-MARKSHEET.
05 STUDENT-ENTRY OCCURS 3 TIMES.
10 STUDENT-NAME PIC X(30).
10 STUDENT-MARKS.
15 FRENCH-MARK PIC 99.
15 MATH-MARK PIC 99.
15 ENGLISH-MARK PIC 99.
15 HISTORY-MARK PIC 99.
01 WS-INDEX PIC 9(3) VALUE 1.
PROCEDURE DIVISION.
MAIN-PROCEDURE.
MOVE "Alice 85 90 78 88" TO STUDENT-ENTRY(1).
MOVE "Bob 75 80 70 85" TO STUDENT-ENTRY(2).
MOVE "Charlie 90 95 92 89" TO STUDENT-ENTRY(3).
OPEN OUTPUT OUTPUT-FILE
PERFORM WRITE-CSV-HEADER
PERFORM VARYING WS-INDEX FROM 1 BY 1
UNTIL WS-INDEX > 3
PERFORM WRITE-STUDENT-ROW
END-PERFORM
CLOSE OUTPUT-FILE
DISPLAY "CSV file 'students.csv' has been created."
STOP RUN.
WRITE-CSV-HEADER.
MOVE "Name,French,Math,English,History" TO OUTPUT-RECORD
WRITE OUTPUT-RECORD.
WRITE-STUDENT-ROW.
STRING
STUDENT-NAME(WS-INDEX), ","
FRENCH-MARK OF STUDENT-MARKS(WS-INDEX), ","
MATH-MARK OF STUDENT-MARKS(WS-INDEX), ","
ENGLISH-MARK OF STUDENT-MARKS(WS-INDEX), ","
HISTORY-MARK OF STUDENT-MARKS(WS-INDEX)
INTO OUTPUT-RECORD
END-STRING
WRITE OUTPUT-RECORD.
Explanation
-
OUTPUT-FILE: The program writes the CSV content into a file named students.csv.
-
STUDENTS-MARKSHEET: Contains hardcoded sample data for three students. The data for other students can be added or modified as needed.
-
WRITE-CSV-HEADER: Writes the column headers to the CSV file.
-
WRITE-STUDENT-ROW: Uses the STRING statement to concatenate each student's data into a CSV format (Name,Mark1,Mark2,...) and writes it to the CSV file.
-
Close and display: Completes the operations by closing the file and notifying the completion.
After running this program, a students.csv file will be created. You can open this file using Excel, and it will automatically interpret the CSV format into a spreadsheet format, displaying the students' marks in a table layout. This method is straightforward and leverages Excel's ability to handle CSV files efficiently.