【问题标题】:Formatting and overriding the default cell format of date & time while writing it in an Excel Sheet在 Excel 工作表中写入日期和时间时格式化和覆盖默认单元格格式
【发布时间】:2020-03-20 06:49:14
【问题描述】:

我们正在捕获包含所有数据的$("#dvtablerptTDetails")[0].innerHTML 中的整个表数据,并且相同的数据将保存在会话中,然后转换为字符串并发送到Response.Write(),稍后将创建一个包含文件类型数据的 Excel 文件xlsx

这里的要求是在写入数据时覆盖默认的单元格格式,特别是对于单个单元格的日期和时间格式。

默认情况下,保存和查看时,
单元格格式为dd/mm/yyyy hh:mm
但预期的单元格格式应为 dd-MMM-yyyy HH:mm:ss

所以尝试用点(.)或按速率(@)修改数据前缀和后缀。但它可以按照我们的要求进行打印。但无法转义特殊字符。因为它完全按原样写。

下面是部分sn-ps

DateTimeUtility objDTU = new DateTimeUtility();
RegisteredDate = objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"])).ToString("dd-MMM-yyyy HH:mm:ss");

public DateTime GetActualDateTime(DateTime utcDateTime)
{
    DateTime actualDateTime;
    if (HttpContext.Current.Session["UserTimeZone"] != null)
    {
        actualDateTime = utcDateTime.AddHours(Double.Parse(HttpContext.Current.Session["UserTimeZone"].ToString(), CultureInfo.InvariantCulture));
    }
    else
    {
        actualDateTime = utcDateTime;
    }
    return actualDateTime;

} 

试图修改分配给RegisteredDate对象的上述数据

objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
  • 实际数据(html) : 28-Feb-2020 15:14:38
  • 实际数据(xsl) : 28/02/2020 15:14
  • 预期数据(xsl):2020 年 2 月 28 日 15:14:38
objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
  • 实际数据(html):2020 年 2 月 28 日 15:14:38.313
  • 实际数据(xsl):14:38。
  • 预期数据 (xsl):2020 年 2 月 28 日 15:14:38.313
objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss");
  • 实际数据(html) : 28-Feb-2020 15:14:38
  • 实际数据(xsl) : 28/02/2020 15:14:38
  • 预期数据(xsl):2020 年 2 月 28 日 15:14:38

下面的编码 sn-ps 显示了 html 数据如何被捕获并遍历到Response.Write()

function ExportAnalysis() {
    try {
        var batchDetails = $("#displayDetails").html();
        var message = JSON.stringify({ BatchDetails: batchDetails });
        CallAjaxJSON(message, '<%=Request.ApplicationPath%>' + "/MES/TestCentre.aspx/PersistBatchDetails", OnExportBatchSuccess, OnFailure);
        var url = '<%=Context.Request.ApplicationPath%>' + '/MES/ExportToExcel.aspx?name=Analysis Response';
        window.open(url);

    } catch (e) {
    }
    return false;
}


[System.Web.Services.WebMethod()]
public static string PersistBatchDetails(object BatchDetails)
{
    try
    {
        HttpContext.Current.Session["DashboardBatchInfo"] = BatchDetails;
    }
    catch (Exception ex){}
    return "S001";
}


protected void Page_Load(object sender, EventArgs e)
{
    string fileName = "Excel";
    if (!String.IsNullOrEmpty(Request.QueryString["name"]))
        fileName = Request.QueryString["name"];
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    string BatchDetails = Convert.ToString(Session["DashboardBatchInfo"]);
    Response.Write(BatchDetails);
    Response.End();
    Session["DashboardBatchInfo"] = null;
}

我们应该如何以各自的格式写出预期的数据?

【问题讨论】:

  • 使用EPPlus 并阅读this。看起来您只是将 html 字符串导出为 xls

标签: c# asp.net datetime export-to-excel


【解决方案1】:

终于找到了解决办法:

[System.Web.Services.WebMethod()]
public static string PersistBatchDetails(object BatchDetails)
{
    try
    {
        string pattern = @"\d{4}\-\d{2}\-\d{2}\s\d{2}\:\d{2}\:\d{2}|\d{2}\-[a-zA-Z]{3}\-\d{4}\s\d{2}\:\d{2}\:\d{2}";
        Regex r = new Regex(pattern);
        var res = r.Replace(BatchDetails.ToString(), new MatchEvaluator(ConvertDateFormat));
        HttpContext.Current.Session["DashboardBatchInfo"] = res;

    }
    catch (Exception ex)
    {
        BasePage objBasePage = new BasePage();
        objBasePage.Log.LogError("Page: TestActivation, Method: GetBatchesList " + ex.Message, ex);
        objBasePage = null;
        return "S002";
    }
    return "S001";
}

public static string ConvertDateFormat(Match m)
{
    var mydate = DateTime.Parse(m.Value);
    return string.Format("=\"{0}\"", mydate.ToString("yyyy-MM-dd hh:mm:ss"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2022-11-25
    • 2014-01-09
    相关资源
    最近更新 更多