在Excel单元格中强制字符串格式

时间:2022-02-07 20:24:02

I'm currently exporting to Excel a RadGrid and I have some cells that have the text "1 / 10" meaning that they had 1 hour used for 10 units. When this gets to Excel, it thinks the cell is a date, so it changes the cell to be January-10 which is not what I'm wanting.

我目前正在向Excel中导出一个RadGrid,我有一些文本“1/10”的单元格意味着它们有1个小时用于10个单位。当它到达Excel时,它认为单元格是一个日期,因此它将单元格更改为1月10日,这不是我想要的。

I've gone the other direction before (changing a string to a number/date) but I've never had the issue where I needed to make Excel keep the cell as a string and not try to change the format.

我之前已经走了另一个方向(将字符串更改为数字/日期)但我从未遇到过需要使Excel将单元格保持为字符串并且不尝试更改格式的问题。

How do I do this? I've tried adding a apostrophe to the beginning of the cell text:

我该怎么做呢?我试过在单元格文本的开头添加一个撇号:

e.Cell.Text = String.Format("'{0}", e.Cell.Text);

but that seems to just make Excel display two apostrophe's at the start of the cell:

但这似乎只是让Excel在单元格的开头显示两个撇号:

在Excel单元格中强制字符串格式


Update:

更新:

I'm using Telerik RadGrid (v2012.2.929.40) and all it does is generate some HTML for Excel to open (you always get that horrible prompt from Excel when trying to open it). So before, if I wanted something to be formatted as a number like I had specific in the grid, I could have the following event that would set the mso-number-format. But, this doesn't quite work when I want Excel to display the cell value as strictly text.

我正在使用Telerik RadGrid(v2012.2.929.40),它所做的就是生成一些用于打开Excel的HTML(当你试图打开它时,你总是会从Excel中得到那个可怕的提示)。所以之前,如果我想要将某些内容格式化为类似我在网格中具体的数字,我可以使用以下事件来设置mso-number格式。但是,当我希望Excel将单元格值显示为严格文本时,这不太有效。

    protected void RadGridQuote_ExcelExportCellFormatting(object sender, ExcelExportCellFormattingEventArgs e)
    {
        if (e.Cell.Style["mso-number-format"] != null)
        {
            e.Cell.Style["mso-number-format"] = "/@";
            e.Cell.HorizontalAlign = HorizontalAlign.Left;
        }
    }

1 个解决方案

#1


1  

If you're using Excel Automation in C#, I've found the best results would be to set the NumberFormat first, which you should set to "@". Then set the value in your .Text property. (If you do it in reverse, it'll convert the date into a number, which you don't want.)

如果你在C#中使用Excel Automation,我发现最好的结果是首先设置NumberFormat,你应该设置为“@”。然后在.Text属性中设置值。 (如果你反向执行,它会将日期转换为你不想要的数字。)

See also MSDN regarding NumberFormat.

另请参阅有关NumberFormat的MSDN。

#1


1  

If you're using Excel Automation in C#, I've found the best results would be to set the NumberFormat first, which you should set to "@". Then set the value in your .Text property. (If you do it in reverse, it'll convert the date into a number, which you don't want.)

如果你在C#中使用Excel Automation,我发现最好的结果是首先设置NumberFormat,你应该设置为“@”。然后在.Text属性中设置值。 (如果你反向执行,它会将日期转换为你不想要的数字。)

See also MSDN regarding NumberFormat.

另请参阅有关NumberFormat的MSDN。