2015-11-09 101 views
0

我試圖在將數據添加到數據表格時使用.ToString()導出Excel文件。 Excel文件單元格格式不是文本,而是格式爲General。這是我的代碼。如何在導出Excel文件時將單元格格式指定爲「文本」

public static void CreateExcel(string filename,System.Data.DataTable table) 
{ 
    if (filename != "") 
    { 
     Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
     xlApp.DisplayAlerts = false; 

     if (xlApp == null) 
     { 
      return; 
     } 

     Workbook xlWorkBook; 
     Worksheet xlWorkSheet; 
     object misValue = System.Reflection.Missing.Value; 

     xlWorkBook = xlApp.Workbooks.Add(misValue); 
     xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1); 

     int Row = table.Rows.Count; 
     int Column = table.Columns.Count; 

     for (int i = 0; i <= Column - 1; i++) 
     { 
      xlWorkSheet.Cells[1, i + 1] = table.Columns[i].ToString(); 
     } 

     for (int i = 0; i <= Row - 1; i++) 
     { 
      for (int j = 0; j <= Column - 1; j++) 
      { 
       xlWorkSheet.Cells[i + 2, j + 1] = table.Rows[i][j].ToString(); 
      } 
     } 

     xlWorkBook.SaveAs(@filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue); 

     xlWorkBook.Close(); 
     xlApp.Quit(); 
     Marshal.FinalReleaseComObject(xlWorkSheet); 
     Marshal.FinalReleaseComObject(xlWorkBook); 
     Marshal.FinalReleaseComObject(xlApp); 

     GC.Collect(); 
    } 
} 

有什麼方法可以改變單元格格式嗎?

+0

在Excel UI中編輯單元格時,只需通過單引號(')字符開始值即可強制文本格式。當通過代碼設置時,這也許有用嗎? –

+0

@modal_dialog這對我很有用。 THK – Kenz

回答

0
// Pull in all the cells of the worksheet 
    Range cells = xlWorkBook.Worksheets[1].Cells; 
    // set each cell's format to Text 
    cells.NumberFormat = "@"; 

這裏有2個鏈接,將幫助你在每一個條件。 Link 1 & Link 2

你的情況:

for (int i = 0; i <= Row - 1; i++) 
     { 
      for (int j = 0; j <= Column - 1; j++) 
      { 
       xlWorkSheet.Cells[i + 2, j + 1] = table.Rows[i][j].ToString(); 
       //It will set each cell while iterates, 
       //I suggest, if its for all column, then set it for the excel sheet. 
       //or if you have a known range, then set for the range. 
       xlWorkSheet.Cells[i + 2, j + 1].NumberFormat = "@"; 
      } 
     } 
1

設置單元格的數字格式將幫助你細胞類型轉換爲文本。

Excel.Worksheet ws = workBook.Worksheets[1]; 
ws.Range["A2"].NumberFormat = "0"; 
相關問題