Benutzer-Werkzeuge

Webseiten-Werkzeuge


c-sharp:datagridview_nach_csv_exportieren

DataGridView nach CSV exportieren

//csvFileWriter = StreamWriter
//scannerDataGridView = DataGridView   
 
private void button1_Click(object sender, EventArgs e)
{
    string CsvFpath = @"C:\folder\CSV-EXPORT.csv";
    try
    {
        System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
 
        string columnHeaderText = "";
 
        int countColumn = scannerDataGridView.ColumnCount - 1;
 
        if (countColumn >= 0)
        {
            columnHeaderText = scannerDataGridView.Columns[0].HeaderText;
        }
 
        for (int i = 1; i <= countColumn; i = i + 1)
        {
            columnHeaderText = columnHeaderText + ',' + scannerDataGridView.Columns[i].HeaderText;
        }
 
 
        csvFileWriter.WriteLine(columnHeaderText);
 
        foreach (DataGridViewRow dataRowObject in scannerDataGridView.Rows)
        {
            if (!dataRowObject.IsNewRow)
            {
                string dataFromGrid = "";
 
                dataFromGrid = dataRowObject.Cells[0].Value.ToString();
 
                for (int i = 1; i <= countColumn; i = i + 1)
                {
                    dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
 
                    csvFileWriter.WriteLine(dataFromGrid);
                }
            }
        }
 
 
        csvFileWriter.Flush();
        csvFileWriter.Close();
    }
    catch (Exception exceptionObject)
    {
        MessageBox.Show(exceptionObject.ToString());
    }

Link zur Quelle

c-sharp/datagridview_nach_csv_exportieren.txt · Zuletzt geändert: 2024/05/16 20:29 von 127.0.0.1