导出数据表到Excel后使用Microsoft.office.interop.Excel日期格式问题

时间:2015-02-07 08:08:00

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

除了导出后excel文件中的日期字段外,我的完整代码运行良好。我将日期字段作为dd / MM / yyyy数据传递给数据表,但在excel中我遇到了几行问题。例如:如果2015年2月份的日期是2015年2月1日至2015年2月12日期间,那么它将在导出的Excel文件中显示为02/01/2015 - 02/12/2015。但如果日期大于或等于13/02/2015那么它显示完美。请帮忙。

这是我写的类文件:

public class InteropExportToExcel
{
public InteropExportToExcel()
{

}

public static void ExportExcel(DataTable dt, string SetFileName)
{
    if (dt == null || dt.Rows.Count == 0) return;

    var xlApp = new Excel.Application();
    //Is this used?
    CultureInfo CurrentCI = Thread.CurrentThread.CurrentCulture;

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

    Excel.Workbooks workbooks = xlApp.Workbooks;

    Excel.Range range;

    Excel.Workbook workbook = workbooks.Add();
    Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

    long totalCount = dt.Rows.Count;
    long rowRead = 0;
    float percent = 0;

    for (var i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;

        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
        range.Interior.ColorIndex = 15;
        range.Font.Bold = true;
    }

    for (var r = 0; r < dt.Rows.Count; r++)
    {
        for (var i = 0; i < dt.Columns.Count; i++)
        {
            worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
        }

        rowRead++;

        //is this used?
        percent = ((float)(100 * rowRead)) / totalCount;
    }

    Microsoft.Office.Interop.Excel.Range columns = worksheet.UsedRange.Columns;
    columns.AutoFit();

    //worksheet.Rows[1].Insert();
    Excel.Range newRow = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[1];
    Excel.Range newCell = (Microsoft.Office.Interop.Excel.Range)newRow.Cells[1];
    //newCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
    //xlApp.Visible = true;
    string fileName = HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName+".xlsx");    //Deleting Previous TempFile Before Saving.

    if (fileName != null || fileName != string.Empty)
    {
        if ((System.IO.File.Exists(fileName)))
        {
            System.IO.File.Delete(fileName);
        }

    }

    workbook.SaveAs(HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  //Saving Current Excel Report in TempFile Server Folder 

    workbook.Close();
    String FileName = SetFileName + ".xlsx";    // Code to Open Save Dialog in Client Computer.
    String FilePath = HttpContext.Current.Server.MapPath("~/TempFiles/");
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "application/ms-excel";
    response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
    response.TransmitFile(FilePath + FileName);
    response.Flush();
    response.End();
}

public static DataTable ConvertToDataTable<T>(IList<T> data)
{
    PropertyDescriptorCollection properties =
       TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        table.Rows.Add(row);
    }
    return table;

}
}

从linkBut​​ton的Click事件中调用此类的方法:

protected void lnkExportToExcel_lnkExportToExcel(object sender, EventArgs e)
    {
        int CustomPageSize = 99999999;
        int CustomPageNumber = 1;
        string FromDate = txtFromDate.Text;
        string ToDate = txtToDate.Text;
        List<int> OutputVal = new List<int>();
        DataTable dtDailyComments = new DataTable();
        PageSize = gvDailyComments.PageSize;
        dtDailyComments = UserClass.GetDailyComments(FromDate, ToDate, CustomPageNumber, CustomPageSize, ref OutputVal);

        var resultSet = from row in dtDailyComments.AsEnumerable() //Selecting Custom Selected Columns From DataTable
                        select new
                        {
                            SlNo = row["SlNo"].ToString(),
                            Comment_Date = row["CommentDate"].ToString(),
                            Subject = row["CommentSubject"].ToString(),
                            Comment = row["Comment"].ToString()

                        };
    string SetFileName = "Daily_Comments_Report";
    DataTable newDataTable = InteropExportToExcel.ConvertToDataTable(resultSet.ToList());
    InteropExportToExcel.ExportExcel(newDataTable, SetFileName);

}

我设法通过以106格式转换数据库中的日期列来解决此问题。但为什么我不能使用数据库中的103格式。那是dd / MM / yyyy。如果可能的话请告诉我如何处理这个问题。

1 个答案:

答案 0 :(得分:1)

如果您想将格式设置为dd / MM / yyyy,请尝试以下操作:

...

{"items": []}