40

当我将值从数据表复制到 Excel 工作表时,我丢失了前导零。那是因为可能 Excel 将值视为数字而不是文本。

我正在复制这样的值:

myWorksheet.Cells[i + 2, j] = dtCustomers.Rows[i][j - 1].ToString();

如何将整列或每个单元格格式化为文本?

一个相关的问题,如何myWorksheet.Cells[i + 2, j] 在 Intellisense 中强制转换以显示样式属性?

4

9 回答 9

50

下面是一些将列 A 和 C 格式化为 .NET 的 SpreadsheetGear 中的文本的代码,它具有类似于 Excel 的 API - 除了 SpreadsheetGear 经常被强类型化。弄清楚如何将其转换为使用 Excel / COM 应该不难:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

免责声明:我拥有 SpreadsheetGear LLC

于 2010-01-14T22:34:56.013 回答
14

如果在添加带有前导零的数值之前将单元格格式设置为文本,则会保留前导零,而无需通过添加撇号来扭曲结果。如果您尝试手动将前导零值添加到 Excel 中的默认工作表,然后将其转换为文本,则会删除前导零。如果您先将单元格转换为文本,然后添加您的值,就可以了。以编程方式执行此操作时适用相同的原则。

        // Pull in all the cells of the worksheet
        Range cells = xlWorkBook.Worksheets[1].Cells;
        // set each cell's format to Text
        cells.NumberFormat = "@";
        // reset horizontal alignment to the right
        cells.HorizontalAlignment = XlHAlign.xlHAlignRight;

        // now add values to the worksheet
        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
            {
                DataGridViewCell cell = dataGridView1[j, i];
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value.ToString();
            }
        }
于 2013-12-30T02:50:01.320 回答
6

在写入 Excel 之前需要更改格式:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
于 2014-08-06T14:24:31.573 回答
6

适用于 Excel 互操作的解决方案:

myWorksheet.Columns[j].NumberFormat = "@";      // column as a text
myWorksheet.Cells[i + 2, j].NumberFormat = "@"; // cell as a text

此代码应在将数据放入 Excel之前运行。列号和行号从 1 开始。

更多细节。尽管已接受的对 SpreadsheetGear 参考的响应看起来几乎是正确的,但我对此有两个担忧:

  1. 我没有使用 SpreadsheetGear。我对通过 Excel 互操作进行常规 Excel 通信感兴趣,而无需任何 3rdparty 库,
  2. 我正在寻找按数字格式化列的方法,而不是使用像“A:A”这样的范围。
于 2016-02-08T22:41:09.743 回答
4

我最近也在与这个问题作斗争,我从上述建议中学到了两点。

  1. 将 numberFormatting 设置为 @ 会导致 Excel 将值左对齐,并像读取文本一样读取它,但是,它仍然会截断前导零。
  2. 在开头添加撇号会导致 Excel 将其视为文本并保留零,然后应用默认文本格式,从而解决这两个问题。

误导的方面是您现在在单元格中具有不同的值。幸运的是,当您复制/粘贴或导出到 CSV 时,撇号不包括在内。

结论:使用撇号而不是 numberFormatting 以保留前导零。

于 2012-04-03T22:12:01.197 回答
2
   if (dtCustomers.Columns[j - 1].DataType != typeof(decimal) && dtCustomers.Columns[j - 1].DataType != typeof(int))
   {
      myWorksheet.Cells[i + 2, j].NumberFormat = "@";
   }
于 2012-12-19T16:44:24.817 回答
2

使用您的WorkSheet.Columns.NumberFormat,并将其设置为string "@",这是示例:

Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "@";

注意:此文本格式将适用于您的孔 Excel 表!

如果您希望特定列应用文本格式,例如第一列,您可以这样做:

workSheet.Columns[0].NumberFormat = "@";

或者这会将指定范围的 woorkSheet 应用于文本格式:

workSheet.get_Range("A1", "D1").NumberFormat = "@";
于 2016-09-30T16:55:42.127 回答
2

我知道这个问题已经过时了,但我还是想做出贡献。

应用Range.NumberFormat = "@"只是部分解决问题:

  • 是的,如果您将焦点放在范围内的一个单元格上,您将阅读格式菜单中的文本
  • 是的,它将数据向左对齐
  • 但是如果你使用类型公式检查单元格中值的类型,它会返回1 含义数字

应用撇号表现更好。它将格式设置为text,它将数据向左对齐,如果您使用类型公式检查单元格中值的格式,它将返回2 含义文本

于 2019-03-08T13:42:33.873 回答
0
//where [1] - column number which you want to make text

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


//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.

  //path were excel file is kept


     string 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);
于 2017-11-10T06:12:25.690 回答