DataGridview从不同形式的Excel到C#

DataGridview to excel from different forms c#
2021-06-10
  •  译文(汉语)
  •  原文(英语)

我有一个Windows c#应用程序,该应用程序具有一个显示访问数据库的dataGridview.当我单击"报告"按钮时,我希望显示一个小的弹出表单,该表单会检查管理员密码,并且如果通过身份验证,则应将gridview导出到excel工作表.但是,这不会发生,因为我认为gridview和login是两种不同的形式.

 private void button1_Click(object sender, EventArgs e)
    {

        try
        {

            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dell\Documents\Database5.accdb;Jet OLEDB:Database Password=sudeep;");
            con.Open();
            OleDbCommand cmd = new OleDbCommand("select * from Login where id='" + textBox1.Text + "' and pass='" + textBox2.Text + "'", con);
            OleDbDataReader dr = cmd.ExecuteReader();
            if (dr.Read() == true)
            {
                //MessageBox.Show("Login Successful");
                this.Visible = false;
                //Form4 frm = new Form4();
                //frm.Show();
                //Form1 fr = new Form1();
                //fr.Dispose(true);
                Form2 frm2 = new Form2();
                frm2.Show();

                this.Close();
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc1));
                t.Start();



                Microsoft.Office.Interop.Excel.Application ExcelApp =
         new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel._Workbook ExcelBook;
                Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;

                int i = 0;
                int j = 0;

                //create object of excel
                ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
                ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
                //export header
                for (i = 1; i <= frm2.dgv.Columns.Count; i++)
                {
                    ExcelSheet.Cells[1, i] = frm2.dgv.Columns[i - 1].HeaderText;
                }

                //export data
                for (i = 1; i <= frm2.dgv.RowCount; i++)
                {
                    for (j = 1; j <= frm2.dgv.ColumnCount; j++)
                    {
                        ExcelSheet.Cells[i + 1, j] = frm2.dgv.Rows[i - 1].Cells[j - 1].Value;
                    }
                }

                ExcelApp.Visible = true;

                //set font Khmer OS System to data range
                Microsoft.Office.Interop.Excel.Range myRange = ExcelSheet.get_Range(
                                          ExcelSheet.Cells[1, 1],
                                          ExcelSheet.Cells[frm2.dgv.RowCount + 1,
                                          frm2.dgv.ColumnCount + 1]);
                Microsoft.Office.Interop.Excel.Font x = myRange.Font;
                x.Name = "Arial";
                x.Size = 10;

                //set bold font to column header
                myRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, 1],
                                         ExcelSheet.Cells[1,frm2.dgv.Columns.Count]);
                x = myRange.Font;
                x.Bold = true;
                //autofit all columns
                myRange.EntireColumn.AutoFit();

                //
                ExcelSheet = null;
                ExcelBook = null;
                ExcelApp = null;


           }
            else
            {
                MessageBox.Show("Login as adminstrator to generate report");
            }
        }

我的datagridview在表单2上,我试图从表单3访问它,即登录表单我已经使用了公共datagridview dgv {get; set}命令,但应用程序仍然无法打开.请帮忙

速聊1:
gridview或datagridview?
速聊2:
datagridview *不是gridview
速聊3:
您如何将数据从一种形式传递到另一种形式?请同时向我们显示该代码.谢谢,
解决过程1

您可以在要使用datagridview的类中添加以下行:

System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["FormName"]; // form name where you have dgv

并通过以下方式调用dgv:

((FormName)f).dgv.Rows.Count

在要获取dgv详细信息的位置更改此位置.尝试一次

速聊1:
仍然存在相同的错误"System.Null引用异常"对象未设置为对象的实例.
解决过程2

尝试此操作,而不是使用互操作,您可以执行此操作以生成excel可以轻松读取的CSV:

在您的datagridview所在的form2中,执行以下操作:

public DataGridView DgReport = new DataGridView();

private void buttonReport_Click()
{
    //assuming your dataGridview is already populated
    DgReport = yourDataGridview;

    Form3 form3 = new Form3(this);
    form3.ShowDialog();
    form3.Dispose();
}

在Form3中:

private Form2 _form2 {get;set;}

public Form3(Form2 form2)
{
    _form2 = form2;
}


private buttonGenerateReport_Click()
{
    int columnsCount;

    var writer = new StreamWriter("test.csv");

    //get number of columns
    columnsCount = _form2.DgReport.Columns.Count;
    for (int i = 0; i < columnsCount - 1; i++)
    { 
        writer.Write(_form2.DgReport.Columns[i].Name.ToString().ToUpper() + ",");
    } 
    writer.WriteLine();

    //write on excel
    for (int i = 0; i < (_form2.DgReport.Rows.Count - 1); i++)
    { 
        for (int j = 0; j < columnsCount; j++)
        { 
            if (_form2.DgReport.Rows[i].Cells[j].Value != null)
            {
                writer.Write(_form2.DgReport.Rows[i].Cells[j].Value + ",");
            }
            else 
            {
                writer.Write(",");
            }
        }

        writer.WriteLine();
    }

    //close file
    writer.Close();
}
速聊1:
我得到的错误是'System.Null reference Exception'对象未设置为对象的实例...这是与dgv相关的错误吗?
速聊2:
您如何将数据从一种形式传递到另一种形式?请同时向我们显示该代码.
速聊3:
我在form2中以"public datagridview dgv = {get; set}"的形式编写了一条命令,然后通过frm2(form2的对象)从另一种形式访问datagridview.
速聊4:
您现在遇到什么错误,在哪一行?而且,如果您可以发布您正在使用的代码,那将很棒

I have a windows c# application which has a dataGridview which displays access database. When i click 'Report' button i want a small pop up form to be displayed which checks administrator password and if authenticated the gridview should be exported to excel sheet. However this is not happening as i guess gridview and login are two different forms.

 private void button1_Click(object sender, EventArgs e)
    {

        try
        {

            OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dell\Documents\Database5.accdb;Jet OLEDB:Database Password=sudeep;");
            con.Open();
            OleDbCommand cmd = new OleDbCommand("select * from Login where id='" + textBox1.Text + "' and pass='" + textBox2.Text + "'", con);
            OleDbDataReader dr = cmd.ExecuteReader();
            if (dr.Read() == true)
            {
                //MessageBox.Show("Login Successful");
                this.Visible = false;
                //Form4 frm = new Form4();
                //frm.Show();
                //Form1 fr = new Form1();
                //fr.Dispose(true);
                Form2 frm2 = new Form2();
                frm2.Show();

                this.Close();
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc1));
                t.Start();



                Microsoft.Office.Interop.Excel.Application ExcelApp =
         new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel._Workbook ExcelBook;
                Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;

                int i = 0;
                int j = 0;

                //create object of excel
                ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
                ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
                //export header
                for (i = 1; i <= frm2.dgv.Columns.Count; i++)
                {
                    ExcelSheet.Cells[1, i] = frm2.dgv.Columns[i - 1].HeaderText;
                }

                //export data
                for (i = 1; i <= frm2.dgv.RowCount; i++)
                {
                    for (j = 1; j <= frm2.dgv.ColumnCount; j++)
                    {
                        ExcelSheet.Cells[i + 1, j] = frm2.dgv.Rows[i - 1].Cells[j - 1].Value;
                    }
                }

                ExcelApp.Visible = true;

                //set font Khmer OS System to data range
                Microsoft.Office.Interop.Excel.Range myRange = ExcelSheet.get_Range(
                                          ExcelSheet.Cells[1, 1],
                                          ExcelSheet.Cells[frm2.dgv.RowCount + 1,
                                          frm2.dgv.ColumnCount + 1]);
                Microsoft.Office.Interop.Excel.Font x = myRange.Font;
                x.Name = "Arial";
                x.Size = 10;

                //set bold font to column header
                myRange = ExcelSheet.get_Range(ExcelSheet.Cells[1, 1],
                                         ExcelSheet.Cells[1,frm2.dgv.Columns.Count]);
                x = myRange.Font;
                x.Bold = true;
                //autofit all columns
                myRange.EntireColumn.AutoFit();

                //
                ExcelSheet = null;
                ExcelBook = null;
                ExcelApp = null;


           }
            else
            {
                MessageBox.Show("Login as adminstrator to generate report");
            }
        }

My datagridview is on form 2 and i am trying to access it from form 3 ie login form I have used the public datagridview dgv {get;set} command as well still the application does not open. Please help

Talk1:
gridview or datagridview?
Talk2:
datagridview* not gridview
Talk3:
How do you pass the data from one form to another? Please show us also that code. thanks,
Solutions1

You can add the following line in the class where u want to use the datagridview :

System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["FormName"]; // form name where you have dgv

and call the dgv by following :

((FormName)f).dgv.Rows.Count

Change this where u want to fetch the dgv details. Try it once

Talk1:
the same error persists ''System.Null reference Exception' object is not set to an instance of an object.'
Solutions2

Try this, instead of using interop, you can do this to generate CSV that can read easily by excel:

in your form2 where datagridview resides do this:

public DataGridView DgReport = new DataGridView();

private void buttonReport_Click()
{
    //assuming your dataGridview is already populated
    DgReport = yourDataGridview;

    Form3 form3 = new Form3(this);
    form3.ShowDialog();
    form3.Dispose();
}

In Form3:

private Form2 _form2 {get;set;}

public Form3(Form2 form2)
{
    _form2 = form2;
}


private buttonGenerateReport_Click()
{
    int columnsCount;

    var writer = new StreamWriter("test.csv");

    //get number of columns
    columnsCount = _form2.DgReport.Columns.Count;
    for (int i = 0; i < columnsCount - 1; i++)
    { 
        writer.Write(_form2.DgReport.Columns[i].Name.ToString().ToUpper() + ",");
    } 
    writer.WriteLine();

    //write on excel
    for (int i = 0; i < (_form2.DgReport.Rows.Count - 1); i++)
    { 
        for (int j = 0; j < columnsCount; j++)
        { 
            if (_form2.DgReport.Rows[i].Cells[j].Value != null)
            {
                writer.Write(_form2.DgReport.Rows[i].Cells[j].Value + ",");
            }
            else 
            {
                writer.Write(",");
            }
        }

        writer.WriteLine();
    }

    //close file
    writer.Close();
}
Talk1:
The error i get is 'System.Null reference Exception' object is not set to an instance of an object...is this an error related to dgv ?
Talk2:
How do you pass the data from one form to another? Please show us also that code.
Talk3:
i wrote a command in form2 as 'public datagridview dgv= {get;set}' and i access datagridview from another form by frm2(object of form2).dgv
Talk4:
what error are you getting now and on what line? And also if you can post the code you are using that would be great
转载于:https://stackoverflow.com/questions/19063902/datagridview-to-excel-from-different-forms-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入