如何在VSTO中关闭Excel自动格式设置

本文关键字:Excel 格式 设置 VSTO | 更新日期: 2023-09-27 18:30:09

我正在用C#开发一个Excel VSTO项目。Excel将自动将类似"SEP-1"的代码格式化为日期,这不是应该发生的事情。有没有办法在代码中的电子表格上关闭此功能?谢谢

如何在VSTO中关闭Excel自动格式设置

虽然似乎没有办法关闭它,但我发现最好的解决方案是将单元格的NumberFormat设置为Text,以防止Excel自动格式化它。

您可以在文本值前面加一个引号。

下面的代码片段是作为伪代码提供的,以了解如何在c#中完成。

Excel.Range vsto_cell = vsto_worksheet.Cells[row_index + 1, col_index + 1];
if( ( ssg_cell.NumberFormatType == SpreadsheetGear.NumberFormatType.Date )
   || ( ssg_cell.NumberFormatType == SpreadsheetGear.NumberFormatType.DateTime )
   || ( ssg_cell.NumberFormatType == SpreadsheetGear.NumberFormatType.Time ) )
{
   vsto_cell.Value2 = ssg_cell.Text; //date should be recognized by Excel as a date
}
else if( ssg_cell.ValueType == SpreadsheetGear.ValueType.Text )
{
   vsto_cell.Value2 = "'" + ssg_cell.Text;
}
else
   vsto_cell.Value2 = ssg_cell.Value;