NPOI日期格式单元格

时间:2014-01-22 04:05:32

标签: c# date format cell npoi

我正在使用NPOI在Sheet1中创建固定工作表模板,并且需要Sheet2中的日期格式数据。我从数据库生成DataTable以在Sheet2中设置数据。 这是我的代码:

private DataTable getWeek()
{    
  strConn = WebConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
  conn = new OdbcConnection(strConn);
  conn.Open();
  sql = "SELECT week, sunday, saturday FROM tb_weekreferences";     
  da = new OdbcDataAdapter(sql, conn);
  dt = new DataTable();
  da.Fill(dt);
  conn.Close();        

  return dt;

}

然后将DataTable导出到Excel:

private int ExportDataTableToExcel(DataTable sourceTable, ISheet sheet)
    {
        IRow headerRow = sheet.CreateRow(0);
        ICell headerCell;
        ICell cell = null;
        Dictionary<String, ICellStyle> styles = CreateExcelStyles(hssfwb);

        //handling value
        int rowIdx = 1;
        foreach (DataRow row in sourceTable.Rows)
        {
            IRow dataRow = sheet.CreateRow(rowIdx);            
            foreach (DataColumn column in sourceTable.Columns)
            {
                cell = dataRow.CreateCell(column.Ordinal);                
                cell.SetCellValue(row[column].ToString());
                cell.CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
                cell.CellStyle = styles["cell"]; 
            }            
            rowIdx++;
        }

        //handling header
        foreach (DataColumn column in sourceTable.Columns)
        {
            headerCell = headerRow.CreateCell(column.Ordinal);
            headerCell.SetCellValue(column.ColumnName);
            headerCell.CellStyle = styles["header"];
            sheet.AutoSizeColumn(column.Ordinal);
            sheet.SetColumnWidth(column.Ordinal, (sheet.GetColumnWidth(column.Ordinal) + (5 * 256))); // set width = autofit() + (5 * 256)
        }
        return rowIdx;
    }

在Sheet1中,我使用vlookup公式从Sheet2获取'sunday'和'saturday'。但它不起作用,因为Sheet2中的星期,星期日和星期六的值似乎是字符串(左对齐单元格)。生成数据到excel时如何在日期中设置单元格格式? 请给我解决方案。

感谢。

1 个答案:

答案 0 :(得分:17)

第一个问题是这一行

cell.SetCellValue(row[column].ToString());

您正在将值转换为字符串,但您可能将其转换为DateTime格式,因此NPOI知道这是日期时间。

或试试这是否有效:

cell.SetCellValue(DateTime.Now);

其次,首先尝试为您的单元格设置样式,然后将其更改为DataFormat属性,但使用如下自定义格式:

IDataFormat dataFormatCustom = workbook.CreateDataFormat();
cell.CellStyle = styles["cell"]; 
cell.CellStyle.DataFormat = dataFormatCustom.GetFormat("yyyyMMdd HH:mm:ss");

将日期时间值格式化为人类可读格式。

相关问题