gpt4 book ai didi

c# - NPOI 日期格式单元格

转载 作者:太空狗 更新时间:2023-10-29 23:58:55 29 4
gpt4 key购买 nike

我正在使用 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数据时如何设置日期单元格格式?请给我解决方案。

谢谢。

最佳答案

第一个问题是这条线

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");

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

关于c# - NPOI 日期格式单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21273949/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com