将数据导出到excel

时间:2018-11-26 03:41:15

标签: c# mysql excel

我知道已经讨论了这个主题,但是我认为它有一些差异。我的数据库中存储了日期。因此,当我将数据表导出到EXCEL时,它就像图像一样显示。

这是EXCEL文件的图像:

enter image description here

我只需要添加日期。不包括HH:MM:SS。我的代码粘贴在下面:

Microsoft.Office.Interop.Excel._Application app = new 
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "InternDetails";

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

for (int i = 0; i < dataGridView3.Rows.Count; i++){
    for (int j = 0; j < dataGridView3.Columns.Count; j++){
        worksheet.Cells[i + 2, j + 1] = dataGridView3.Rows[i].Cells[j].Value.ToString();
    }
}

var saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Interns";
saveFileDialog.DefaultExt = ".xlsx";

if (saveFileDialog.ShowDialog() == DialogResult.OK){
    workbook.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

好吧,如果您只想显示日期而没有时间,则应设置数字格式。 只是看这样的代码: SomeCell.NumberFormat="yyyy-mm-dd"

它将显示例如:“ 2018-05-20”

答案 1 :(得分:0)

如果我错了,请纠正我,对于我在提供的屏幕截图中看到的内容,它由3个日期列组成,分别为statusdatefplacementdateperiodcomplertion

您尝试过这种方式吗?

首先为您的日期创建一个转换函数。

public static string convertDateFormat(this string date)
{
                DateTime dateFormat = Convert.ToDateTime(date);
                if (dateFormat != DateTime.MinValue)
                {
                    return String.Format("{0:MM/dd/yyyy}", dateFormat);
                }
                else
                {
                    return "";
                }
}

然后以这种方式使用

for (int i = 0; i < dataGridView3.Rows.Count; i++){
    for (int j = 0; j < dataGridView3.Columns.Count; j++){
        string formatValue = dataGridView3.Rows[i].Cells[j].Value.ToString();

        if( dataGridView3.Columns[j].HeaderText == "statusdate" || dataGridView3.Columns[j].HeaderText == "fplacementdate" || dataGridView3.Columns[j].HeaderText == "periodcomplertion"){
           formatValue.convertDateFormat();
        }

        worksheet.Cells[i + 2, j + 1] = formatValue;
    }
}