我正在动态创建一个excel表并将值插入到同一个.但是某些单元格中的值以错误的格式插入.
以下是我的Excel表格
所选单元格中的值应为0002-9343,但它将插入到Feb-43.这是由于excel表格中该列(列-D)的格式错误.
在输入数据之前,我需要将整个列-D(标题D“data2”下的所有单元格)更改为“文本格式”.
以下是创建Excel工作表和插入数据的代码
以下是我的Excel表格
所选单元格中的值应为0002-9343,但它将插入到Feb-43.这是由于excel表格中该列(列-D)的格式错误.
在输入数据之前,我需要将整个列-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,false,XlSaveAsAccessMode.xlShared,null);
- wb.Close(true);
- 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#?
要更改整个列的格式,请使用此选项
- // 4 is for Col D
- sheet.Cells[1,4].EntireColumn.NumberFormat = "@";
请记住在尝试写入之前格式化Col D.使用.EntireColumn将确保您不必单独更改Excel单元格的格式:)