user3056503
user3056503

Reputation: 7

Convert string to date from an excel file asp.net mvc

After putting this code and importing excel file, I'm always encountering data tables with no values even though most of the rows has values in the excel file. My problem is to convert string (ex. 20131022) to date (yyyyMMdd) after importing excel file and show "N/A" as the value if it is null or 0.

Here's my code:

//AdminController.cs

if (data.ordDate == "0" || data.ordDate == null)
{
Response.Write("N/A");
}
else
{
data.ordDate = ds.Tables[0].Rows[i]["ordDate"].ToString();
}

if (data.paymentDate == "0" || data.paymentDate == null)
{
Response.Write("N/A");
}
else
{
data.paymentDate = ds.Tables[0].Rows[i]["paymentDate"].ToString();
}

//ExcelData.cs

public class ExcelData
    {
        public string ordDate { get; set; } 
        public string paymentDate { get; set; }
    }

//_ExcelData.cshtml

@model IEnumerable<ExcelData>

<table class="table table-striped table-bordered bootstrap-datatable">
    <thead>
        <tr>
            <th>Order Date</th>
            <th>Payment Date</th>

        </tr>
    </thead>
    <tbody>
        @try
        {
            foreach (var data in Model)
            {
            <tr>
                <td>@data.ordDate</td>
                <td>@data.paymentDate</td>           
            </tr>
            }
        }
        catch
        {
            <tr>
                <td colspan="5">No data available.</td>
            </tr>
        }
    </tbody>
</table>

Can you help me guys with this? My whole day is so f*** up with this code. I'm new in ASP.NET MVC. I tried the other format but still it shows nothing except for the row of N/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/AN/A on the top of the data table.

Thanks in advance to those who are willing to help! :)

Upvotes: 0

Views: 1968

Answers (1)

Chris
Chris

Reputation: 339

I think you could create a method to deal with it:

public static string ConvertDateTime(string data)
{
    DateTime dateTime;
    return DateTime.TryParseExact(data
        , "yyyyMMdd"
        , CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime) 
        ? dateTime.ToString("yyyyMMdd") : "N/A";
}

or without format checking:

public static string ConvertDateTime(string data)
{
    return data == "0" || string.IsNullOrWhiteSpace(data) ? "N/A" : data;
}

and your main method(AdminController.cs) can use it to get the datetime value:

data.ordDate = ConvertDateTime(ds.Tables[0].Rows[i]["ordDate"].ToString());
data.paymentDate = ConvertDateTime(ds.Tables[0].Rows[i]["paymentDate "].ToString());

Upvotes: 2

Related Questions