如何在c#中更改Excel列的格式?

前端之家收集整理的这篇文章主要介绍了如何在c#中更改Excel列的格式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在动态创建一个excel表并将值插入到同一个.但是某些单元格中的值以错误的格式插入.
以下是我的Excel表格
所选单元格中的值应为0002-9343,但它将插入到Feb-43.这是由于excel表格中该列(列-D)的格式错误.
在输入数据之前,我需要将整个列-D(标题D“data2”下的所有单元格)更改为“文本格式”.
以下是创建Excel工作表和插入数据的代码
  1. excel = new Application();
  2. excel.Visible = false;
  3. wb = (_Workbook)(excel.Workbooks.Add(System.Reflection.Missing.Value));
  4. sheet = wb.Sheets.Add();
  5. sheet.Name = "TestSheet1";
  6. sheet.Cells[1,"A"].Value2 = "Id";
  7. sheet.Cells[1,"B"].Value2 = "Name";
  8. sheet.Cells[1,"C"].Value2 = "Data1";
  9. sheet.Cells[1,"D"].Value2 = "Data2";
  10. sheet.Cells[1,"E"].Value2 = "Data3";
  11.  
  12. for (int i = 0; i < 10; i++)
  13. {
  14. id = i;
  15. result = object;
  16. data = JsonConvert.DeserializeObject(result);
  17.  
  18. name = (data != null) ? data.name : string.Empty;
  19. data1 = (data != null) ? data.data1 : string.Empty;
  20. data2 = (data != null) ? data.data2 : string.Empty;
  21. data3 = (data != null) ? data.data3 : string.Empty;
  22.  
  23. sheet.Cells[i + 2,"A"].Value2 = name;
  24. sheet.Cells[i + 2,"B"].Value2 = data1;
  25. sheet.Cells[i + 2,"C"].Value2 = data2;
  26. sheet.Cells[i + 2,"D"].Value2 = data3;
  27. }
  28. string ExcelPath = Some_path;
  29. wb.SaveAsExcelPath,XlFileFormat.xlWorkbookNormal,null,false,XlSaveAsAccessMode.xlShared,null);
  30. wb.Close(true);
  31. excel.Quit();

现在,在循环之前,我需要将Column-D下的单元格格式更改为Text Format.
如何从c#代码中做同样的事情?

解决方法

Now,before the loop I need to change the format of cells under Column-D to Text Format. How to do the same from code in c#?

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

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

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

猜你在找的C#相关文章