简体   繁体   English

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

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

My full Code is working well except the date field in the excel file after exporting. 我的完整代码运行良好,除了导出后Excel文件中的日期字段。 i am passing the date field as dd/MM/yyyy data with data table but in excel i am having an issue for few rows. 我将日期字段作为dd / MM / yyyy数据与数据表一起传递,但是在Excel中,我遇到了几行的问题。 for example :in case of February month of 2015 if the date is in between 01/02/2015 to 12/02/2015 then it is showing as 02/01/2015 - 02/12/2015 in exported excel file . 例如:如果是2015年2月,则日期在2015年2月1日至2015年2月2日之间,则导出的excel文件中的日期将显示为02/01/2015-02/12/2015。 but if date is greater than or equal to 13/02/2015 then it is showing perfect. 但如果日期大于或等于2015年2月13日,则显示为完美。 Please help. 请帮忙。

This is the class file i wrote : 这是我写的课程文件:

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;

}
}

Calling the method of this class from the linkButton's Click event : 从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);

}

I managed to fix this issue by converting the date columns from database in 106 format. 我设法通过以106格式转换数据库中的日期列来解决此问题。 but why cant i use 103 format from database. 但是为什么我不能从数据库中使用103格式。 that is dd/MM/yyyy. 就是dd / MM / yyyy。 if possible then please tell me how to handle this issue. 如果可能的话,请告诉我如何处理此问题。

If you like to set the format to dd/MM/yyyy try this: 如果您想将格式设置为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();
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Microsoft.Office.Interop.Excel SaveAs 错误导出到 .xlsx - Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error 使用Microsoft.Office.Interop.Excel将数据集导出到xlsx - Exporting dataset to xlsx with Microsoft.Office.Interop.Excel C#使用microsoft.office.interop.excel在widndows表单上将电子邮件导出到excel - C# exporting e-mails to excel on widndows forms using microsoft.office.interop.excel 使用 Microsoft.Office.Interop.Excel 加快性能导出到 Excel 文件 - speed performance exporting to excel file using Microsoft.Office.Interop.Excel 使用Microsoft.Office.Interop.Excel导出Excel时出错 - Error when export Excel using Microsoft.Office.Interop.Excel Office 2007的Microsoft.Office.Interop.Excel - Microsoft.Office.Interop.Excel for Office 2007 使用Excel = Microsoft.Office.Interop.Excel编译错误 - using Excel = Microsoft.Office.Interop.Excel Compilation Error 在 c# 中使用 Microsoft.Office.Interop.Excel 在 excel 列中设置数字、文本和日期等数据类型 - Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c# 在C#中使用Microsoft.Office.Interop.Excel将数据Excel移至40行数据后的右列 - Move data Excel to Right Column after 40 Rows Data using Microsoft.Office.Interop.Excel in C# 使用 Microsoft.Office.Interop.Excel 的问题:无法加载文件或程序集 &#39;office,版本 = 15.0.0.0 - Issue using Microsoft.Office.Interop.Excel: Could not load file or assembly 'office, Version=15.0.0.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM