【问题标题】:Change number to text format in excel in windows c#在windows c#中的excel中将数字更改为文本格式
【发布时间】:2013-04-26 15:11:26
【问题描述】:

我正在将数据从 datagridview 导出到 Excel 工作表。数据由数字和字符组成。数字显示在单元格的最右侧,与左侧的字符一样。我缺少一些数字格式。我希望数字也显示在单元格的另一侧。下面是导出到excel的代码。

 private void button3_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
      Excel.Range oRange;

        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range aRangeSingle = xlWorkSheet.get_Range("A1", "A1");
        aRangeSingle.ColumnWidth = 37;

        Excel.Range aRangeSingle2 = xlWorkSheet.get_Range("B1", "B1");
        aRangeSingle2.ColumnWidth = 65;



        int i = 0;
        int j = 0;
        try
        {

            for (i = 0; i <= dataGridView2.RowCount - 1; i++)
            {
                for (j = 0; j <= dataGridView2.ColumnCount - 1; j++)
                {
                    DataGridViewCell cell = dataGridView2[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;//this has numbers also


                }
            }

        }
        catch (Exception)
        {
            MessageBox.Show("server not available while export to excel");
        } 

【问题讨论】:

  • 您需要设置单元格的水平对齐属性。 oRange.Horizo​​ntalAlignment
  • 不是您具体问题的答案,但请查看stackoverflow.com/questions/5059757/…。您可以填充比 2 for 循环快得多的 Excel 范围。关于您的问题:使用@andy 的解决方案。应该这样工作。

标签: c# windows excel


【解决方案1】:

将您的行更改为:

xlWorkSheet.Cells[i + 1, j + 1] = "'" + cell.Value;

如果 excel 在开头看到单引号,它会将其假定为 TEXT。但是在这种情况下,计算不会作为数字起作用。如果要用作数字,请将单元格向左对齐

【讨论】:

  • 我试过了,但在 excel 上我看到左上角有一个小标记,表示警告数字已更改为文本。我可以避免吗
猜你喜欢
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多