【问题标题】:C# Excel Interop: How to format cells to store values as textC# Excel 互操作:如何格式化单元格以将值存储为文本
【发布时间】:2011-09-28 13:05:42
【问题描述】:

我正在将数字从DataTable 写入 Excel 电子表格,如果数字本身的长度小于 5 位,所有这些数字的长度都是 5 位,前面有 0(例如,395 将存储为 00395 )。

将这些数字输入 Excel 时(使用 C#),它会将它们存储为数字并消除前面的 0。有什么方法可以从 C# 格式化单元格,以便将值存储为文本而不是数字?

【问题讨论】:

标签: c# excel interop


【解决方案1】:

您可以SomeRange.NumberFormat = "@";,或者如果您在值前面加上' 并将其写入单元格,excel 会将其视为数字存储为文本并提供视觉提示。

【讨论】:

  • 谢谢,已经解决了!非常感谢。
【解决方案2】:

这个答案刚刚解决了我们公司软件中的一个解决方案的一个主要问题,我必须检索显示的值,但是一旦我将它设置为新工作表,它就会作为数字插入。 简单的解决方案。 我还不能投票,但投票结果如下。

for (int h = 1; h <= 1; h++)
{
    int col = lastColl(sheets);
    for (int r = 1; r <= src.Count; r++)
    {
        sheets.Cells[r, col + 1] = "'"+src.Cells[r, h].Text.ToString().Trim();
    }
}

【讨论】:

  • 这有效,而更改 NumberFormat 的解决方案在我的情况下不适用于 FedEx 跟踪代码(14 位数字)。
【解决方案3】:

//其中 [1] 是您要制作文本的列号

ExcelWorksheet.Columns[1].NumberFormat = "@";

//如果要格式化工作簿中所有工作表中的特定列 - 使用下面的代码。删除单张纸的循环以及轻微的变化。

//保存excel文件的路径

字符串 ResultsFilePath = @"C:\Users\krakhil\Desktop\TGUW EXCEL\TEST";

    Excel.Application ExcelApp = new Excel.Application();
    Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
    ExcelApp.Visible = true;

    //Looping through all available sheets
    foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
    {                
        //Selecting the worksheet where we want to perform action
        ExcelWorksheet.Select(Type.Missing);
        ExcelWorksheet.Columns[1].NumberFormat = "@";
    }

    //saving excel file using Interop
    ExcelWorkbook.Save();

    //closing file and releasing resources
    ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
    Marshal.FinalReleaseComObject(ExcelWorkbook);
    ExcelApp.Quit();
    Marshal.FinalReleaseComObject(ExcelApp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多