• XSS.stack #1 – первый литературный журнал от юзеров форума

C# I'm getting an error when trying to export datagridview data to a csv file / C# Я получаю сообщение об ошибке при попытке экспортировать данные dat

danthe

CD-диск
Пользователь
Регистрация
22.02.2022
Сообщения
12
Реакции
3
Гарант сделки
1
hi I don't know Russian thats why I'll use translate for convert my text to Russian so I'm if anything wrong

// English Version //

I want to export the data's in datagridview to csv file I created a class for export option then call class from the button but I'm getting the error
C#:
using System.Windows.Forms;

namespace excel2

    internal class ExportHelper
    {
        public bool Export(DataGridView dgv)
        {
            bool exported = false;

            List<string> lines = new List<string>();
            DataGridViewColumnCollection column = dgv.Columns;
            bool firstDone = false;
            StringBuilder columnLine = new StringBuilder();
            foreach(DataGridViewColumn col in column)
            {
                if(!firstDone)
                {
                    columnLine.Append(col.DataPropertyName);
                    firstDone = true;
                }
                else
                {
                    columnLine.Append("," + col.DataPropertyName);
                }
            }
            lines.Add(columnLine.ToString());

            //data lines
            foreach(DataGridViewRow row in dgv.Rows)
            {
                StringBuilder dataLine = new StringBuilder();
                firstDone = false;
                foreach(DataGridViewCell cell in row.Cells)
                {
                    if (firstDone)
                    {
                        dataLine.Append(cell.Value);
                        firstDone= true;
                    }
                    else
                    {
                        dataLine.Append(","+cell.Value);
                    }
                    lines.Add(dataLine.ToString());
                }

            }
            string file = Path.Combine(Application.StartupPath, "Excel");
            File.WriteAllLines(file,lines); //this line giving error
            System.Diagnostics.Process.Start(file);

            return exported;
        }
    }

the code I attached to button from form
C#:
private void button8_Click(object sender, EventArgs e)
{
    new ExportHelper().Export(dataGridView1);
}

the errror message : System.UnauthorizedAccessException: ''C:\Users\Danthe\Desktop\VisualStudio\excel2\bin\Debug\Excel' Access denied to path.'

// Russian Version //

Я хочу экспортировать данные из datagridview в csv-файл, я создал класс для опции экспорта, затем вызываю класс с помощью кнопки, но я получаю сообщение об ошибке

Код:
using System.Windows.Forms;

namespace excel2

    internal class ExportHelper
    {
        public bool Export(DataGridView dgv)
        {
            bool exported = false;

            List<string> lines = new List<string>();
            DataGridViewColumnCollection column = dgv.Columns;
            bool firstDone = false;
            StringBuilder columnLine = new StringBuilder();
            foreach(DataGridViewColumn col in column)
            {
                if(!firstDone)
                {
                    columnLine.Append(col.DataPropertyName);
                    firstDone = true;
                }
                else
                {
                    columnLine.Append("," + col.DataPropertyName);
                }
            }
            lines.Add(columnLine.ToString());

            //data lines
            foreach(DataGridViewRow row in dgv.Rows)
            {
                StringBuilder dataLine = new StringBuilder();
                firstDone = false;
                foreach(DataGridViewCell cell in row.Cells)
                {
                    if (firstDone)
                    {
                        dataLine.Append(cell.Value);
                        firstDone= true;
                    }
                    else
                    {
                        dataLine.Append(","+cell.Value);
                    }
                    lines.Add(dataLine.ToString());
                }

            }
            string file = Path.Combine(Application.StartupPath, "Excel");
            File.WriteAllLines(file,lines); //this line giving error
            System.Diagnostics.Process.Start(file);

            return exported;
        }
    }

код, который я прикрепил к кнопке из формы

C#:
private void button8_Click(object sender, EventArgs e)
{
    new ExportHelper().Export(dataGridView1);
}

сообщение об ошибке : System.UnauthorizedAccessException: ''C:\Users\Danthe\Desktop\VisualStudio\excel2\bin\Debug\Excel' Access denied to path.'
------------------------------------
Я не знаю русского языка, поэтому я использовал перевод, чтобы перевести его на русский. Мне жаль, если я был неправ
 
The file is opened using another application?
I Don't understand what you mean but let me explain you what I did

I got a 2 form 1 class 4 button

form 1 datagridview 2 button
when I click button 1 it open form2
and when I open form 2 there is a listbox and 2 button
when click the button1 it import my items inside listbox
and when I click the button2 it move items inside listbox to datagridview and back to form1
so what I'm doing after that click button 2 ( in form1) to export/save data inside datagridview
and I'm getting the error I explained my codes and error code at the subject I opened
 
Пожалуйста, обратите внимание, что пользователь заблокирован
I Don't understand what you mean but let me explain you what I
The file is already opened with excel or some other process that locked it.
 
The file is already opened with excel or some other process that locked it.
I solved I was trying to create new file in folder but in my codes its editing current file sorry I missed that
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх