import { APIError } from '../errors/api.error' ; /**
 * Helper exposing useful Utilities for Excel Add-ins.
 */ export class ExcelUtilities { param workbook param sheetName param clearOnly returns static async forceCreateSheet ( workbook , sheetName , clearOnly ? ) { if ( workbook == null && typeof workbook !== typeof Excel . Workbook ) { throw new APIError ( 'Invalid workbook parameter.' ) ; } if ( sheetName == null || sheetName . trim ( ) === '' ) { throw new APIError ( 'Sheet name cannot be blank.' ) ; } if ( sheetName . length > 31 ) { throw new APIError ( 'Sheet name cannot be greater than 31 characters.' ) ; } let sheet ; if ( clearOnly ) { sheet = await createOrClear ( workbook . context as any , workbook , sheetName ) ; } else { sheet = await recreateFromScratch ( workbook . context as any , workbook , sheetName ) ; } await workbook . context . sync ( ) ; return sheet ; } } /**
 * Helpers
 */ async function createOrClear ( context , workbook , sheetName ) { if ( Office . context . requirements . isSetSupported ( 'ExcelApi' , 1.4 ) ) { const existingSheet = context . workbook . worksheets . getItemOrNullObject ( sheetName ) ; await context . sync ( ) ; if ( existingSheet . isNullObject ) { return context . workbook . worksheets . add ( sheetName ) ; } else { existingSheet . getRange ( ) . clear ( ) ; return existingSheet ; } } else { await context . sync ( ) ; try { const oldSheet = workbook . worksheets . getItem ( sheetName ) ; oldSheet . getRange ( ) . clear ( ) ; await context . sync ( ) ; return oldSheet ; } catch ( error ) { if ( error instanceof OfficeExtension . Error && error . code === Excel . ErrorCodes . itemNotFound ) { return workbook . worksheets . add ( sheetName ) ; } else { throw new APIError ( 'Unexpected error while trying to delete sheet.' , error ) ; } } } } async function recreateFromScratch ( context , workbook , sheetName ) { const newSheet = workbook . worksheets . add ( ) ; if ( Office . context . requirements . isSetSupported ( 'ExcelApi' , 1.4 ) ) { context . workbook . worksheets . getItemOrNullObject ( sheetName ) . delete ( ) ; } else { await context . sync ( ) ; try { const oldSheet = workbook . worksheets . getItem ( sheetName ) ; oldSheet . delete ( ) ; await context . sync ( ) ; } catch ( error ) { if ( error instanceof OfficeExtension . Error && error . code === Excel . ErrorCodes . itemNotFound ) { } else { throw new APIError ( 'Unexpected error while trying to delete sheet.' , error ) ; } } } newSheet . name = sheetName ; return newSheet ; }