c#将数据导出到excel时格式化列

guykilcj  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(408)

我知道这个主题已经讨论过了,但我认为有些不同。我的数据库里有日期。因此,当我将数据表导出到excel时,它显示为图像。
以下是excel文件的图像:

我只需要加上日期。不包括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);
}

谢谢你的帮助。

nr9pn0ug

nr9pn0ug1#

纠正我,如果我错了,为我所看到的在提供的屏幕截图,它包括3个日期列,这是 statusdate , fplacementdate 以及 periodcomplertion .
你这样试过吗?
首先为日期创建一个转换函数。

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;
    }
}
acruukt9

acruukt92#

好的,如果您只想显示日期而不想显示时间,您应该设置数字格式。看看下面的代码: SomeCell.NumberFormat="yyyy-mm-dd" 例如:“2018-05-20”

相关问题