NPOI日期格式单元格

Faj*_*hyu 4 c# format date 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;

}
Run Code Online (Sandbox Code Playgroud)

然后将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;
    }
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Jur*_*uri 18

第一个问题是这一行

cell.SetCellValue(row[column].ToString());
Run Code Online (Sandbox Code Playgroud)

您正在将值转换为字符串,但您可能将其转换为DateTime格式,因此NPOI知道这是datetime.

或试试这是否有效:

cell.SetCellValue(DateTime.Now);
Run Code Online (Sandbox Code Playgroud)

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

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

这会将DateTime值格式化为人类可读的格式.