2013-04-04 50 views
6

我正在動態創建一個Excel工作表並將值插入到相同的位置。但某些單元格中的值插入的格式不正確。在所選擇的小區 以下是我的excel表enter image description here 值應在Excel工作表已經0002-9343但它被插入爲FEB-43。這是由於該列(列-d)一些錯誤的格式。 我需要在輸入數據之前將整列-D(標題D「data2」下的所有單元格)更改爲「文本格式」。 以下是循環我需要改變細胞的格式下列-d爲文本格式之前創建excel工作表和插入數據如何更改c#中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(); 

現在,代碼。 如何從c#中的代碼做同樣的事情?

回答

2

這不是您的問題的答案,但我會建議您使用Open XML Api而不是通過Interop使用Excel。 您可以在那裏爲添加到電子表格中的任何單元格定義數據類型。

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

您是否嘗試過使用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;  

會推薦在未來更容易的圖書館。互操作方法是完全有效的,但有時難以像你想要的那樣工作。

5

現在,在循環之前,我需要將列D下的單元格格式更改爲文本格式。如何從C#中的代碼做同樣的事情?

要改變整列的格式使用此

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

記得格式化山口d試圖寫入之前。使用.EntireColumn將確保您不必單獨更改Excel單元格的格式:)