将数据 Table 导出至 Excel 后使用 Microsoft.office.interop.Excel 日期格式问题

Using Microsoft.office.interop.Excel Date format issue after exporting Data Table To Excel

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

这是我写的 class 文件 :

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 事件调用此 class 的方法:

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。如果可能的话,请告诉我如何处理这个问题。

如果您想将格式设置为 dd/MM/yyyy 试试这个:

...

  try
        {
            if (dgvData.Rows.Count > 0)
            {
                xCellApp.Application.Workbooks.Add(Type.Missing);

                for (int i = 1; i < dgvData.Columns.Count + 1; i++)
                {
                    xCellApp.Cells[1, i] = dgvData.Columns[i - 1].HeaderText;
                }

                for (int i = 0; i < dgvData.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < dgvData.Columns.Count; j++)
                    {
                        if (dgvData.Columns[j].HeaderText == "dates")
                        {

                            DateTime dt = Convert.ToDateTime(dgvData.Rows[i].Cells[j].Value.ToString());
                            xCellApp.Cells[i + 2, j + 1] = dt.ToString("MM/dd/yyyy");


                        }
                        else
                        {
                            xCellApp.Cells[i + 2, j + 1] = dgvData.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }

                xCellApp.Columns.AutoFit();

                xCellApp.Visible = true;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            xCellApp.Quit();
        }
    }