簡體   English   中英

使用C#導出文件時,在.xls文件中轉換日期格式

[英]Convert date formate in .xls file, while exporting the file using c#

我正在使用C#.net將數據導出到.xls文件(Excel doc)。 在這里,我有一個日期字段。 現在我想更改日期格式。 Excel文檔中的Diff-Diff日期格式。

protected void ExportToExcel(DataSet ds, string FilePath)
        {
            StreamWriter sw;
            StringBuilder strFileContents = new StringBuilder();
            strFileContents.Append("ID" + "\t" + "ItemName" + "\t" + "Initiated By" + "\t" + "Date of Initiation" + "\t" + "Date of Expiry" + "\t" + "Item Price" + "\t" + "Name" + "\t" + "Phone" + "\t" + "Company" + "\t" + "Address");
            strFileContents.Append("\n");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    strFileContents.Append(row["ID"] + "\t");
                    strFileContents.Append(row["ItemName"] + "\t");
                    strFileContents.Append(row["UserName"] + "\t");
                    strFileContents.Append(row["DealInitiatedOn"] + "\t");
                    strFileContents.Append(row["DealExpiryDate"] + "\t");
                    strFileContents.Append(row["ItemPrice"] + "\t");
                    strFileContents.Append(row["FullName"] + "\t");
                    strFileContents.Append(row["Phone"] + "\t");
                    strFileContents.Append(row["Company"] + "\t");
                    strFileContents.Append(row["Address"] + "\t");
                    strFileContents.Append("\n");
                }
            }
            sw = System.IO.File.CreateText(FilePath);
            sw.Write(ISpace.CommLive.UI.User.CommonFunctions.StripHTMLTags(strFileContents.ToString()));
            sw.Close();
        }

謝謝,賈加迪

DateTime.ToString()方法允許您指定格式設置參數。

string myFormat = "yyyy-mm-dd" // <= your format goes here
strFileContents.Append(((DateTime)row["DealExpiryDate"]).ToString(myFormat) + "\t");

您可以嘗試以下方法嗎

string format = "yyyy-mm-dd";
strFileContents.Append((DateTime.Parse(row["DealExpiryDate"])).ToString(format) + "\t");

如果需要,還可以使用DateTime.TryParse代替Parse函數。

替代方法:

string format = "yyyy-mm-dd";
DateTime? expDate = row.Field<DateTime?>("DealExpiryDate");
if(expDate.HasValue)
{
    strFileContents.Append(expDate.Value.ToString(format) + "\t");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM