Do you want live notifications when people reply to your posts? Passing date value to putValue() and trying to set a date format

Date Values Stored as Text Instead of DateTime in Cells

Issue Description

I’m experiencing an issue with date values in Excel cells using Aspose.Cells. When I programmatically insert a date value into a cell and apply date formatting, the value is initially stored as text rather than as a proper DateTime value.

Current Behavior

  • Date value is inserted into the cell as a string
  • Cell appears to contain the date but Excel treats it as text
  • Only after manually double-clicking the cell does Excel recognize it as a DateTime value
  • Once recognized, the date formatting (style.setNumber(14)) works correctly

Code Sample

// Date handling portion of my cell value function
if (options.isDate) {
  try {
    console.log('Date Value before parsing', value);
    const dateValue = new Date(value);
    console.log('Date Value after parsing', dateValue);
    
    if (!isNaN(dateValue.getTime())) {
      console.log(dateValue, 'is a valid date');
      dateValue.setHours(0, 0, 0, 0);
      console.log(dateValue, 'after setting hours to 0');
      cell.putValue(dateValue);
      console.log(dateValue, 'after putting value in cell');
      
      try {
        style.setNumber(14); // Standard date format
        console.log('Date format set successfully');
      } catch (e) {
        console.error('Primary date formatting failed: ', e);
        // Fallback to custom format
        try {
          style.setCustom('mm/dd/yyyy');
        } catch (innerErr) {
          console.log('Date format fallback failed', innerErr);
        }
      }
    } else {
      console.log('Invalid date value:', value);
      cell.putValue('');
    }
  } catch (err) {
    console.log('Error parsing date value:', err);
    cell.putValue('');
  }
}

Expected Behavior

The date value should be recognized as a DateTime data type immediately after insertion, without requiring manual interaction with the cell.

Questions

  1. Is there a specific method to ensure the cell value is stored as DateTime rather than text?
  2. Should I be using a different approach to insert JavaScript Date objects into cells?
  3. Are there any additional properties or methods I need to set to force Excel to recognize the value as a date?

I have attached the files and image for reference.

Any guidance on properly inserting DateTime values that are immediately recognized by Excel would be greatly appreciated.
image.png (68.1 KB)

@JayaPrakash031

To ensure that date values are stored as DateTime rather than text in Excel cells when using Aspose.Cells, you can follow these guidelines:

  1. Use the Correct Overload of PutValue: When inserting a date value, make sure to use the overload of the PutValue method that accepts a boolean parameter indicating whether to convert the value to the appropriate data type. This will help in storing the date as a numeric value instead of a string. For example:

    cell.putValue(dateValue, true); // The second parameter 'true' converts to the appropriate data type
    
  2. Ensure Proper Date Object Creation: When creating a date object, ensure that it is a valid JavaScript Date object. You can check if the date is valid using isNaN(dateValue.getTime()) as you are already doing.

  3. Setting the Cell Style: After inserting the date, you can set the cell style to format it as a date. You can use built-in number formats or custom formats. For example:

    style.setNumber(14); // Standard date format
    

    If this fails, you can fall back to a custom format:

    style.setCustom('mm/dd/yyyy');
    
  4. Example Code: Here’s a modified version of your code that incorporates these suggestions:

    if (options.isDate) {
      try {
        const dateValue = new Date(value);
        if (!isNaN(dateValue.getTime())) {
          dateValue.setHours(0, 0, 0, 0);
          cell.putValue(dateValue, true); // Ensure it's stored as DateTime
          
          try {
            style.setNumber(14); // Standard date format
          } catch (e) {
            style.setCustom('mm/dd/yyyy'); // Fallback to custom format
          }
        } else {
          cell.putValue(''); // Handle invalid date
        }
      } catch (err) {
        cell.putValue(''); // Handle parsing error
      }
    }
    

By following these steps, the date values should be recognized as DateTime immediately after insertion, without requiring any manual interaction in Excel. If you continue to experience issues, please ensure that the date format you are using is compatible with Excel’s expected formats.

@JayaPrakash031,

Please try using the overload of putValue method that accepts a boolean parameter indicating whether to convert the value to the appropriate data type. Please use the following line when inserting Date values.

cell.putValue(dateValue, true); 

In case you still find the issue, kindly do provide your sample Excel file, we will check it soon.

@amjad.sahi @Professionalize.Discourse

Sorry I have attached my old code,
this is my new code

const addValueToCell = (
  worksheet: any,
  row: number,
  col: number,
  value: any,
  options: {
    isBold?: boolean;
    isCurrency?: boolean;
    fontSize?: number;
    underline?: 'single' | 'double' | '';
    border?: boolean;
    isGrandorInvoiceTotal?: boolean;
    isDate?: boolean;
  } = {}
) => {
  const logTag = '[addValueToCell]';
  try {
    const cell = worksheet.getCells().get(row, col);

    if (value === null || value === undefined || value === '') {
      cell.putValue(''); // Set empty string for null/undefined/empty values
      return;
    } else {
      cell.putValue(value);
    }

    const style = cell.getStyle();

        if (options.isDate) {

          try {
            const dateValue = new Date(value);
    
            if (!isNaN(dateValue.getTime())) {
    
              const month = String(dateValue.getMonth() + 1).padStart(2, '0');
              const day = String(dateValue.getDate()).padStart(2, '0');
              const year = dateValue.getFullYear();
              const dateString = `${month}/${day}/${year}`;
    
              cell.putValue(dateString);
              
              try {
                style.setNumber(14);
                cell.setStyle(style);
    
                console.log(logTag, 'Date format set successfully');
              } catch (e: any) {
                console.error('Approach 1 failed for date formatting: ', e);
                console.log('Using the alternative approach to set the custom format');
                
                try {
                  style.setCustom('mm/dd/yyyy');
                  cell.setStyle(style);
                } catch (innerErr) {
                  console.log(logTag, 'Date format fallback failed', innerErr);
                }
              }
            } else {
              console.log(logTag, 'Invalid date value:', value);
              cell.putValue('');
            }
          } catch (err) {
            console.log(logTag, 'Error parsing date value:', err);
            cell.putValue('');
          }
        }

    if (options.isBold) {
      try {
        // Try the original method first
        style.getFont().setIsBold(true);
      } catch (err) {
        try {
          // Alternative 1
          style.getFont().setBold(true);
        } catch (innerErr) {
          try {
            // Alternative 2
            console.log(logTag, 'setBold not available, trying alternative 2');
            style.getFont().setFontStyle(aspose.cells.FontStyle.Bold);
          } catch (innerErr) {
            console.log(logTag, 'setFontStyle not available');
          }
        }
      }
    }

    if (options.fontSize) {
      try {
        // Try the original method first
        style.getFont().setSize(options.fontSize);
      } catch (err) {
        try {
          // Alternative 1
          console.log(logTag, 'setSize not available, trying alternative 1');
          style.getFont().setFontSize(options.fontSize);
        } catch (innerErr) {
          console.log(logTag, 'setFontSize not available');
        }
      }
    }

    if (options.isCurrency) {
      const roundedValue = Number(parseFloat(value).toFixed(2));
      cell.putValue(Math.abs(roundedValue)); // Use absolute value for display

      try {
        if (roundedValue < 0) {
          style.setCustom('$#,##0.00_);($#,##0.00)');
        } else {
          style.setCustom('$#,##0.00');
        }
      } catch (err) {
        try {
          console.log(logTag, 'setCustom not available, trying alternative 1');
          if (roundedValue < 0) {
            style.setNumber(CURRENCY_STYLE_WITH_PARENTHESES); // Assuming 41 is the index for currency format with parentheses
          } else {
            style.setNumber(CURRENCY_STYLE_INDEX); // Assuming 8 is the index for standard currency format
          }
        } catch (innerErr) {
          console.log(logTag, 'setNumber not available');
        }
      }

      if (roundedValue < 0) {
        cell.putValue(-Math.abs(roundedValue));
      }
    }

    if (options.underline) {
      try {
        style.getFont().setUnderline(options.underline === 'single' ? 1 : 2);
      } catch (err) {
        try {
          console.log(
            logTag,
            'setUnderline not available, trying alternative 1'
          );
          const underlineType =
            options.underline === 'single'
              ? aspose.cells.FontUnderlineType.Single
              : aspose.cells.FontUnderlineType.Double;
          style.getFont().setUnderlineType(underlineType);
        } catch (innerErr) {
          console.log(logTag, 'setUnderlineType not available');
        }
      }
    }

    if (options.border) {
      try {
        const borders = style.getBorders();

        // Set top border
        borders
          .getByBorderType(aspose.cells.BorderType.TOP_BORDER)
          .setLineStyle(aspose.cells.CellBorderType.THIN);
        borders
          .getByBorderType(aspose.cells.BorderType.TOP_BORDER)
          .setColor(aspose.cells.Color.getBlack());

        // Set bottom border
        if (options.isGrandorInvoiceTotal) {
          console.log(options, 'options', 'Bottom Border');
          borders
            .getByBorderType(aspose.cells.BorderType.BOTTOM_BORDER)
            .setLineStyle(aspose.cells.CellBorderType.DOUBLE);
          borders
            .getByBorderType(aspose.cells.BorderType.BOTTOM_BORDER)
            .setColor(aspose.cells.Color.getBlack());
        } else {
          borders
            .getByBorderType(aspose.cells.BorderType.BOTTOM_BORDER)
            .setLineStyle(aspose.cells.CellBorderType.THIN);
          borders
            .getByBorderType(aspose.cells.BorderType.BOTTOM_BORDER)
            .setColor(aspose.cells.Color.getBlack());
        }

        if (!options.isGrandorInvoiceTotal) {
          // Set left border
          borders
            .getByBorderType(aspose.cells.BorderType.LEFT_BORDER)
            .setLineStyle(aspose.cells.CellBorderType.THIN);
          borders
            .getByBorderType(aspose.cells.BorderType.LEFT_BORDER)
            .setColor(aspose.cells.Color.getBlack());

          // Set right border
          borders
            .getByBorderType(aspose.cells.BorderType.RIGHT_BORDER)
            .setLineStyle(aspose.cells.CellBorderType.THIN);
          borders
            .getByBorderType(aspose.cells.BorderType.RIGHT_BORDER)
            .setColor(aspose.cells.Color.getBlack());
        }

        console.log(logTag, 'Borders set successfully');
      } catch (err) {
        console.error(logTag, 'Error setting borders:', err);
        try {
          const borders = style.getBorders();
          borders.setStyle(
            aspose.cells.BorderType.TOP_BORDER,
            aspose.cells.CellBorderType.THIN
          );
          borders.setStyle(
            aspose.cells.BorderType.BOTTOM_BORDER,
            aspose.cells.CellBorderType.THIN
          );
          borders.setStyle(
            aspose.cells.BorderType.LEFT_BORDER,
            aspose.cells.CellBorderType.THIN
          );
          borders.setStyle(
            aspose.cells.BorderType.RIGHT_BORDER,
            aspose.cells.CellBorderType.THIN
          );
          borders.setColor(aspose.cells.Color.getBlack());

          console.log(
            logTag,
            'Individual borders set successfully using alternative method'
          );
        } catch (err2) {
          console.error(
            logTag,
            'Error setting individual borders using alternative method:',
            err2
          );
        }
      }
    }

    cell.setStyle(style);
  } catch (error: any) {
    throw {
      message: 'An while placing the values in the cells : ' + error.message,
      occurredAt: 'addValueToCell',
    };
  }
};

the issue I faced with old code was sometimes, date values were just empty in excel not sure why and didn’t get any errors either

another doubt is when passing the values to putValue() should we pass the date values as date or convert it to string and pass it? or both works in above approach?

@JayaPrakash031,

Yes, even you convert the Date value to string, it will also work provided you use the suggested putValue() overload which has second Boolean parameter which you will always set to “true”.

Let us know if you still have any issue.

@JayaPrakash031
In Excel, a date value consists of a number and a date number format, so if you enter a string value, Excel only can process it as a text. There are some ways to set date time:
1). Set date time and number format

DateTime date = DateTime.Now;
cell.PutValue(date);
style.setNumber(14);
cell.setStyle(style);

2). Set string value and number format:

cell.PutValue("2025/05/27",true);
style.setNumber(14);
cell.setStyle(style);

3). Set string value with its format

cell.PutValue("2025/05/27",true,true);  

The last param means setting the number format (yyyy/mm/dd in above code) to cell’s style when converting to other data type.