【问题标题】:How to change format of a column of excel sheet in c#?如何在c#中更改excel表格一列的格式?
【发布时间】:2013-04-04 08:10:32
【问题描述】:

我正在动态创建一个 Excel 工作表并将值插入其中。但是某些单元格中的值以错误的格式插入。 以下是我的excel表 所选单元格中的值应为 0002-9343,但插入为 Feb-43。这是由于该列(列-D)中的格式错误excel表。 在输入数据之前,我需要将整个 D 列(标题 D“data2”下的所有单元格)更改为“文本格式”。 下面是创建excel表和插入数据的代码

excel = new Application();
            excel.Visible = false;
            wb = (_Workbook)(excel.Workbooks.Add(System.Reflection.Missing.Value));
            sheet = wb.Sheets.Add();
            sheet.Name = "TestSheet1";
            sheet.Cells[1, "A"].Value2 = "Id";
            sheet.Cells[1, "B"].Value2 = "Name";
            sheet.Cells[1, "C"].Value2 = "Data1";
            sheet.Cells[1, "D"].Value2 = "Data2";
            sheet.Cells[1, "E"].Value2 = "Data3";

            for (int i = 0; i < 10; i++)
            {
                    id = i;
                    result = object;
                    data = JsonConvert.DeserializeObject(result);

        name  = (data != null) ? data.name : string.Empty;
                    data1 = (data != null) ? data.data1 : string.Empty;
                    data2 = (data != null) ? data.data2 : string.Empty;
                    data3 = (data != null) ? data.data3 : string.Empty;

                    sheet.Cells[i + 2, "A"].Value2 = name;  
                    sheet.Cells[i + 2, "B"].Value2 = data1; 
                    sheet.Cells[i + 2, "C"].Value2 = data2; 
                    sheet.Cells[i + 2, "D"].Value2 = data3;
            }
            string ExcelPath = Some_path;
            wb.SaveAsExcelPath,XlFileFormat.xlWorkbookNormal, null, null, false, false, XlSaveAsAccessMode.xlShared, false, false, null, null, null);
            wb.Close(true);
            excel.Quit();

现在,在循环之前,我需要将 Column-D 下的单元格格式更改为文本格式。 如何在 c# 中的代码中执行相同的操作?

【问题讨论】:

    标签: c# asp.net asp.net-mvc excel


    【解决方案1】:

    现在,在循环之前,我需要将 Column-D 下的单元格格式更改为文本格式。如何在 c# 中的代码中执行相同的操作?

    要更改整个列的格式,请使用此

    // 4 is for Col D
    sheet.Cells[1, 4].EntireColumn.NumberFormat = "@";
    

    请记住在尝试写入之前格式化 Col D。使用.EntireColumn 将确保您不必单独更改 Excel 单元格的格式:)

    【讨论】:

      【解决方案2】:

      这不是您问题的答案,但我建议您使用 Open XML Api 而不是通过 Interop 使用 excel。 您可以在此处为添加到电子表格的任何单元格定义数据类型。

      Cell c = new Cell();
      c.DataType = CellValues.InlineString;
      

      【讨论】:

        【解决方案3】:

        您尝试过使用 NumberFormat 吗?

        sheet.Cells[i + 2, "D"].NumberFormat = "@";    
        sheet.Cells[i + 2, "A"].Value2 = name;  
        sheet.Cells[i + 2, "B"].Value2 = data1; 
        sheet.Cells[i + 2, "C"].Value2 = data2; 
        sheet.Cells[i + 2, "D"].Value2 = data3;     
        

        建议将来查看更简单的库。互操作方法是完全有效的,但有时更难按您的意愿工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-23
          • 2020-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-10
          • 2012-05-27
          相关资源
          最近更新 更多