2017-08-18 22 views
0

我使用NPOI Excel的庫生成一個Excel文件,在Excel文件我正在顯式定義列類型,如日期列,字符串等NPOI集顯柱類型,使用不正常

林下面的代碼來實現這一點。

var row = sheet.CreateRow(currentNPOIRowIndex++); 
        for (var colIndex = 0; colIndex < exportData.Columns.Count; colIndex++) 
        { 
         ICell cell = null; 
         cell = row.CreateCell(colIndex); 
         if (exportData.Columns[colIndex].DataType == typeof(DateTime)) 
         { 
          if (exportData.Rows[rowIndex][colIndex].ToString() != "") 
          { 
           cell.SetCellValue((DateTime)exportData.Rows[rowIndex][colIndex]); 
           cell.CellStyle = (NPOI.HSSF.UserModel.HSSFCellStyle)book.CreateCellStyle(); 
           cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("yyyyMMdd HH:mm:ss"); 
           cell = null; 
          } 
          else 
           cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString()); 
         } 
         else 
          cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString()); 
        } 
       } 

上面的代碼工作正常,42行,即它正確地設置列類型,但經過42行列類型不適用。

任何幫助將不勝感激。

+0

你可以試試最新的代碼。我已經爲您提供了可行的解決方案。謝謝。 –

回答

0

如果您想爲該列的所有單元格設置列格式,則需要設置默認列樣式。請從xssf格式查看下面的示例。語法可能會因您的hssf格式而有所不同,但它會讓您知道您缺少的內容。

我從我的工作代碼中提供給您。我正在使用NPOI版本2.2.1.0。 你可以註釋// // cell = null;

XSSFWorkbook workbook = new XSSFWorkbook(); 
    XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Template"); 

    XSSFFont defaultFont = (XSSFFont)workbook.CreateFont(); 
    defaultFont.FontHeightInPoints = (short)10; 

    XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle(); 
    headerStyle.WrapText = true; 

    XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle(); 
    XSSFDataFormat defaultDataFormat = (XSSFDataFormat)workbook.CreateDataFormat(); 
    defaultStyle.SetDataFormat(defaultDataFormat.GetFormat("000-000-0000")); 
    defaultStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;     
    defaultStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index; 
    defaultStyle.SetFont(defaultFont); 

    var row = sheet.CreateRow(0); 
    for (int headerCount = 0; headerCount < headers.Count(); headerCount++) 
    { 
     row.CreateCell(headerCount).SetCellValue(headers[headerCount]); 
     row.Cells[headerCount].CellStyle = headerStyle; 
     sheet.SetDefaultColumnStyle(headerCount, defaultStyle);   
    } 
+0

我試過你的解決方案,但仍然存在相同的問題,格式適用於42行。 –