c# - C#中replace方法的问题

标签 c#

我正在用 C# 开发一个应用程序,该应用程序从 MySql 数据库生成 CSV 文件。 我遇到的问题是,当生成 PDF 文件时,日期的格式为“dd/MM/yyyy”,而我想要的是具有类似“dd-MM-yyyy”的格式,这就是为什么在 for 循环内我对行进行“替换”,然后说:

for (int j = 0; j < columnCount; j++)
{
    outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('/', '-') + ";";
    
    if (j == 9 ) //position of the column to be modified
    {
        outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('-','/') + ";";
    }
}

其余代码是这样的:

private void btnexport_Click(object sender, EventArgs e)
{
    if (dataGridView2.Rows.Count > 0)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "CSV (*.csv)|*.csv";
        bool fileError = false;
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            if (File.Exists(sfd.FileName))
            {
                try
                {
                    File.Delete(sfd.FileName);
                }
                catch (IOException ex)
                {
                    fileError = true;
                    MessageBox.Show("No se pueden escribir los datos" + ex.Message);
                }
            }
            if (!fileError)
            {
                try
                {
                    int columnCount = dataGridView2.Columns.Count;
                    string columnNames = "";
                    string[] outputCsv = new string[dataGridView2.Rows.Count +1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        columnNames += dataGridView2.Columns[i].HeaderText.ToString()+";";
                    }
                    outputCsv[0] += columnNames;
                    
                    for (int i = 1; i < dataGridView2.Rows.Count; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            // first I replace in the whole file the "/" by "-"   
                            outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('/', '-') + ";";
                        
                            if (j == 9 ) 
                            {
                                //then I go to position 6 and change ('-','/') as the format of that field must necessarily have the slash ("/")
                                outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('-','/') + ";";
                            }
                        }
                    }
                    File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
                    MessageBox.Show("Fichero generado correctamente", "Atencion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error :" + ex.Message);
                }
            }
        }
    }
    else
    {
        MessageBox.Show("Debes seleccionar unas cuentas", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
        MessageBox.Show("No se ha generado un reporte!!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

结果:

REFERENCE;LAWYER;PORTFOLIO_NAME;CUT_OFF_DATE;PORTFOLIO_NUMBER;NAME;COURT_NUMBER;COURT_CITY;PROCESS_TYPE;COURT_CASE;CONSIGATION_ACCOUNT;
16437;Sara;ADWS;01-01-1900 0:00:00;1;BANK PEN;1;MARTORELL;ETJ;0331-12;0331/12;0782000005033112;
14572;Sara;MLSK;01-01-1900 0:00:00;1;BANK PEN;1;BADALONA;ETJ;4598-16;4598/16;0782000005031897;

预期:(正如我们所看到的,这会以正确和错误的格式重复两次(“0331-12;0331/12”))

REFERENCE;LAWYER;PORTFOLIO_NAME;CUT_OFF_DATE;PORTFOLIO_NUMBER;NAME;COURT_NUMBER;COURT_CITY;PROCESS_TYPE;COURT_CASE;CONSIGATION_ACCOUNT;
    16437;Sara;ADWS;01-01-1900 0:00:00;1;BANK PEN;1;MARTORELL;ETJ;0331/12;0782000005033112;
    14572;Sara;MLSK;01-01-1900 0:00:00;1;BANK PEN;1;BADALONA;ETJ;4598/16;0782000005031897;

我做错了什么??? 谢谢!!

最佳答案

只需检查您的值是否为 DateTime 并相应地设置其格式即可:

if (dataGridView2.Rows[i - 1].Cells[j].Value is DateTime date)
{
    outputCsv[i] += date.ToString("dd-MM-yyyy H:mm:ss") + ";";
}
else
{
    outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString() + ";";
}

下面是一个示例来说明其原理:

using System;
class HelloWorld {
    static void Main() {
        object[] test = { DateTime.Now, "fizzbuzz" };
        
        foreach(var t in test)
        {
            if(t is DateTime date)
            {
                Console.WriteLine(date.ToString("dd-MM-yyyy H:mm:ss"));
            }
            else
            {
                Console.WriteLine("Not a DateTime");
            }
        }
    }
}

写入:

11-08-2021 13:02:20
Not a DateTime

Check it online

关于c# - C#中replace方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68740090/

相关文章:

c# - C# 中的线程和 TcpListener

c# - 制作 C# RegEx 匹配返回意外数据

c# - 如何使用 LINQ 返回 FileInfo.Name 的子字符串

c# - 无法将重复行添加到 asp.net 表控件

c# - WPF应用程序关闭的原因是什么

c# - 定义委托(delegate)蓝图

c# - 非托管内存泄漏

c# - 在 Windows Phone 上设计媒体播放器的好方法是什么?

c# - 当 POCO 文件位于单独的项目中时将 EF 指向数据库

c# - 如何使自定义标题栏上的无边框表单可拖动?