【问题标题】:Excel always returning Date Format dd-MM-yy instead of dd-MM-yyyyExcel 总是返回日期格式 dd-MM-yy 而不是 dd-MM-yyyy
【发布时间】:2020-07-01 16:19:16
【问题描述】:

我需要使用 DataTable动态创建 Excel 表头。为此,我正在使用以下函数。

using (XLWorkbook wb = new XLWorkbook())
{
   DataTable dt = new DataTable();

   if (Module == "Employee Basic")
   {
      dt = fnEmployeeBasicFields();
   }

   wb.Worksheets.Add(dt, "Import");

   Response.Clear();
   Response.Buffer = true;
   Response.Charset = "";
   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   Response.AddHeader("content-disposition", "attachment;filename=Import.xlsx");

   using (MemoryStream MyMemoryStream = new MemoryStream())
   {
       wb.SaveAs(MyMemoryStream);
       MyMemoryStream.WriteTo(Response.OutputStream);
       Response.Flush();
       Response.End();
   }

}

用户在 Excel 表中输入数据后,我需要将数据导入 DataTable。我正在使用以下功能

DataTable dt = new DataTable();
            
using (XLWorkbook workbook = new XLWorkbook(path))
{
   IXLWorksheet worksheet = workbook.Worksheet(1);
   bool FirstRow = true;
                
   string readRange = "1:1";
   foreach (IXLRow row in worksheet.RowsUsed())
   {
      if (FirstRow)
      {
         readRange = string.Format("{0}:{1}", 1, row.LastCellUsed().Address.ColumnNumber);
         foreach (IXLCell cell in row.Cells(readRange))
         {
            dt.Columns.Add(cell.Value.ToString());
         }
         FirstRow = false;
       }
       else
       {
          dt.Rows.Add();
          int cellIndex = 0;
                        
          foreach (IXLCell cell in row.Cells(readRange))
          {
               DateTime date;
               if (cell.TryGetValue(out date))
               {
                  // Check if cell is datetime type and do something
                  cellIndex++;
               }
               else
               {
                   dt.Rows[dt.Rows.Count - 1][cellIndex] = cell.Value.ToString();
                   cellIndex++;
               }
           }
        }
   }
}

我面临的问题是,无论我以何种方式格式化 Excel,我总是以 dd-MM-yy hh:mm:ss 格式从 excel 获取 DateTime 数据。我需要 dd/MM/yyyy 格式的日期格式化列会改变它在 Excel 工作表中的显示方式,但不会改变它返回值的方式。

感谢您的宝贵时间,如果可能的话,感谢您的帮助。

【问题讨论】:

  • 这些只是显示格式。在内部,它被保存为一个数字。只需将 OleDb 与 ACE 驱动程序一起使用即可获取数据。您还可以使用 NuGet 中的 Epplus 和 LinqToExcel 库。

标签: c# asp.net excel closedxml


【解决方案1】:

您将所有值都视为字符串。因此,日期格式不相关。检查您的数据表的每个列的数据类型是否正确。您可以在Columns.Add() 重载中指定数据类型。如果您省略数据类型,则默认为string,随后会以字符串形式填充到您的XLWorksheet。

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 2012-03-05
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多