我正在使用 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 中获取“星期日”和“星期六”。但它不起作用,因为 Sheet2 中的星期、星期日和星期六的值看起来像字符串(左对齐单元格)。生成数据到excel时如何设置日期单元格格式?请给我解决方案。
谢谢。