Function to create a file name for exported Excel document

The requirement was to generate unique and valid file names for Microsoft Excel files. The name should contain the data title and date/time when the data was exported. Here is the code I used for creating the file names for Excel documents:

function fileNameCreate(title: string): string {

 // Remove invalid characters, replace spaces with underscore

 const validTitle = title.replace(/[<>:”/|?*]+/g, ).replace(/s/g, ‘_’);

 const date = new Date();

 const dateTime = (date.getMonth() + 1) + ‘-‘ + date.getDate() + ‘-‘ + date.getFullYear() + ‘_’ + date.getHours().toString().padStart(2, ‘0’) + ‘.’ + date.getMinutes().toString().padStart(2, ‘0’) + ‘.’ + date.getSeconds().toString().padStart(2, ‘0’);

 return validTitle + ‘_’ + dateTime;

}

Leave a comment

Your email address will not be published. Required fields are marked *