3
我正在使用NPOI在Sheet1中创建固定工作表模板,并需要使用日期格式的Sheet2中的数据。我从数据库生成DataTable以在Sheet2中设置数据。 这是我的代码:NPOI日期格式单元格
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;
}
,然后导出数据表到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的 '星期六'。但它不起作用,因为Sheet2中星期,星期日和星期六的值看起来像字符串(左对齐单元格)。如何在生成数据为excel时设置日期单元格格式? 请给我这个解决方案。
谢谢。
现在会得到日期,但我需要从其他工作表中获取日期。 –
而我已经尝试过你的第二个代码,它不起作用,通过vlookup公式,仍然像sheet2中那样格式化单元格(作为字符串)。 –
所以好像你在Sheet2中有问题。当您从数据库填充Sheet2(在查找之前)时,是否可以将该日期转换为DataTime格式?你有什么格式的数据库? 也许在您读取ith getWeek()方法的DataTable中,您可以创建一些DateTime格式的日期而不是字符串的临时列,并将其用于查找? – Juri