通过运行脚本在在线Excel中获取下一个工作日

问题描述 投票:0回答:1

有人可以帮助我使用 sharepoint excel 脚本吗?

我正在尝试通过执行脚本来获取下一个工作日的在线 Excel 表格。

条件:如果是节假日或周末或时间超过下午 5 点(均为美国东部时间),则应在 C3 单元格中给出下一个工作日。

我尝试在本地计算机中使用宏,但业务需要在在线 Excel 上使用它。

屏幕截图示例:

enter image description here

我期望输出为06/26/24,但得到输出06/24/24(假期)

function main(workbook: ExcelScript.Workbook) {
    console.log("Script started");
    CheckHolidayOrWeekend(workbook);
    console.log("Script finished");
}

function CheckHolidayOrWeekend(workbook: ExcelScript.Workbook) {
    let sheetName = "Sheet1"; // Change to your sheet name
    let ws: ExcelScript.Worksheet = workbook.getWorksheet(sheetName);

    if (!ws) {
        console.log(`Worksheet with name '${sheetName}' not found`);
        return;
    }
    console.log(`Worksheet '${sheetName}' accessed`);

    // Get the used range of column A
    let range: ExcelScript.Range = ws.getUsedRange().getColumn(1);

    if (!range) {
        console.log("No values found in column A");
        return;
    }

    console.log(`Values in range A:A: ${JSON.stringify(range.getValues())}`);

    let flattenedValues: (string | number | boolean)[] = [].concat(...range.getValues());
    let lastRow: number = flattenedValues.filter(value => Boolean(value)).length;
    console.log(`Last row in column A with data: ${lastRow}`);

    // Get current date and time
    let currentDate: Date = new Date();
    let currentTime: string = `${currentDate.getHours()}:${("0" + currentDate.getMinutes()).slice(-2)}`;
    console.log(`Current date: ${currentDate}, Current time: ${currentTime}`);
    let isHoliday: boolean = false;

    // Function to check if a date is in the holiday list
    const isDateInRange = (date: Date, range: ExcelScript.Range): boolean => {
        let rangeValues: (string | number | boolean)[][] = range.getValues();
        console.log(`Checking range: ${range.getAddress()}`);
        console.log(`Range values: ${JSON.stringify(rangeValues)}`);

        if (!rangeValues || rangeValues.length === 0) {
            return false;
        }
        for (let i = 0; i < rangeValues.length; i++) {
            if (rangeValues[i][0] && new Date(rangeValues[i][0].toString()).toDateString() === date.toDateString()) {
                return true;
            }
        }
        return false;
    };

    // Check if today is a holiday
    let checkRangeSize = 100; // Adjust the chunk size as needed
    for (let i = 1; i <= lastRow; i += checkRangeSize) {
        let endRow = Math.min(i + checkRangeSize - 1, lastRow);
        let holidaysRange = ws.getRange(`A${i}:A${endRow}`);
        if (isDateInRange(currentDate, holidaysRange)) {
            isHoliday = true;
            break;
        }
    }

    // Determine the next working date
    let nextWorkingDate: Date = new Date(currentDate);

    if (isHoliday || currentDate.getDay() === 0 || currentDate.getDay() === 6 || currentTime > "17") {
        do {
            nextWorkingDate.setDate(nextWorkingDate.getDate() + 1);

            // Check if the next day is a holiday
            isHoliday = false;
            for (let i = 1; i <= lastRow; i += checkRangeSize) {
                let endRow = Math.min(i + checkRangeSize - 1, lastRow);
                let holidaysRange = ws.getRange(`A${i}:A${endRow}`);
                if (isDateInRange(nextWorkingDate, holidaysRange)) {
                    isHoliday = true;
                    break;
                }
            }
        } while (isHoliday || nextWorkingDate.getDay() === 0 || nextWorkingDate.getDay() === 6);
    }

    // Format the next working date
    let formattedDate: string = `${("0" + (nextWorkingDate.getMonth() + 1)).slice(-2)}/${("0" + nextWorkingDate.getDate()).slice(-2)}/${nextWorkingDate.getFullYear().toString().slice(-2)}`;
    console.log(`Next working date: ${formattedDate}`);

    // Write the result in cell C3 
    ws.getRange("C3 ").setValue(formattedDate);
    console.log("Result written to C3");
}

    
javascript typescript office-scripts
1个回答
0
投票
  • Excel 和 JavaScript 中的日期表示不同。在 Excel 中,日期按自 1900 年 1 月 1 日起的天数计算(单元格中显示的日期实际上存储为这些序列号)。
  • 另一方面,JavaScript 使用自 1970 年 1 月 1 日以来经过的毫秒数作为其日期参考点。
// Function to check if a date is in the holiday list
    const isDateInRange = (date: Date, range: ExcelScript.Range): boolean => {
        let rangeValues: (string | number | boolean)[][] = range.getValues();
        console.log(`Checking range: ${range.getAddress()}`);
        console.log(`Range values: ${JSON.stringify(rangeValues)}`);

        if (!rangeValues || rangeValues.length === 0) {
            return false;
        }
        let converted = 25569.0 + ((date.getTime() - (date.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
        console.log(Math.floor(converted))
        return rangeValues.some(cellValue => cellValue.includes(Math.floor(converted)));
        // for (let i = 0; i < rangeValues.length; i++) {
        //  if (rangeValues[i][0] && new Date(rangeValues[i][0].toString()).toDateString() === date.toDateString()) {
        //      return true;
        //  }
        // }
        // return false;
    };
© www.soinside.com 2019 - 2024. All rights reserved.