简体   繁体   English

将datagridview数据导出到Excel工作表

[英]Exporting datagridview data into Excel Worksheet

Am working on a project and I need to export datagridview data into an excel sheet.我正在做一个项目,我需要将 datagridview 数据导出到 excel 表中。 My datagridview has 38 columns and about 120 rows(with spaces between the words) and the data is entered from the datagridview.我的 datagridview 有 38 列和大约 120 行(单词之间有空格),数据是从 datagridview 输入的。 When I run the app, I get this Exception, " Object reference not set to an instance of an object.".当我运行该应用程序时,我收到此异常,“Object 引用未设置为 object 的实例。”。 This is my code block:这是我的代码块:

private void exportbtn_Click(object sender, EventArgs e)私人无效exportbtn_Click(对象发送者,EventArgs e)

        if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
        {
            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            ExcelApp.Application.Workbooks.Add(Type.Missing);
            ExcelApp.Columns.AutoFit();

            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                   ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
                MessageBox.Show("Data Exported Successfully");
            }
            ExcelApp.ActiveWorkbook.SaveAs("");
            ExcelApp.ActiveWorkbook.Saved = true;              
            ExcelApp.Visible = true;
            ExcelApp.Quit();
         
         }

And I populated the datagridview first column(Facillity) as:我将datagridview第一列(Facillity)填充为:

        ArrayList row = new ArrayList();
        row.Add("Techiman Holy Family Hospital"); dataGridView1.Rows.Add(row.ToArray());
        row = new ArrayList();
        row.Add("Opoku Agyeman Hospital"); dataGridView1.Rows.Add(row.ToArray());
        row = new ArrayList();
        row.Add("Kintampo Municipal Hospital"); dataGridView1.Rows.Add(row.ToArray());

Also I don't want to choose new excel workbook anytime am exporting to excel.此外,我不想在导出到 excel 的任何时候选择新的 excel 工作簿。 I want to save all sheets in the same workbook.我想将所有工作表保存在同一个工作簿中。 Is there a way to edit the following code to achieve that:有没有办法编辑以下代码来实现:

        saveFileDialog1.InitialDirectory = ("C:");
        saveFileDialog1.Title = "Save as Excel File";
        saveFileDialog1.FileName = "";
        saveFileDialog1.Filter = "Excel Files(2003)|*.xls| Excel Files(2007)|*.xlsx";

Please any help?请问有什么帮助吗? Thanks.谢谢。

First of all, I suggest that you can refer to the following code to add data to your datagridview.首先,我建议你可以参考下面的代码来给你的datagridview添加数据。

 private void Form1_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Hospital");
            table.Columns.Add("Name");
            table.Columns.Add("Age");
            table.Columns.Add("Address");
            table.Columns.Add("Id");
            table.Columns.Add("Sex");
            table.Rows.Add("Techiman Holy Family Hospital", "test11", "22","home","1001","Man");
            table.Rows.Add("Techiman Holy Family Hospital", "test2", "23", "home", "1001", "Man");
            table.Rows.Add("Opoku Agyeman Hospital", "test8", "22", "home", "1001", "Man");
            table.Rows.Add("Opoku Agyeman Hospital", "test6", "26", "home", "1001", "Man");
            table.Rows.Add("Kintampo Municipal Hospital", "test21", "22", "home", "1001", "Man");
            table.Rows.Add("Kintampo Municipal Hospita", "test12", "22", "home", "1001", "Man");
            dataGridView1.DataSource = table;
        }

Second, the key point to solve the problem is that we need to change dataGridView1.Rows.Count to dataGridView1.Rows.Count-1 because the datagirdview will generate one empty row automatically.其次,解决问题的关键是我们需要将dataGridView1.Rows.Count更改为dataGridView1.Rows.Count-1 ,因为datagirdview会自动生成一个空行。

Finally, here is a code example you can refer to.最后,这是一个您可以参考的代码示例。

 private void button1_Click(object sender, EventArgs e)
        {
            saveFileDialog1.InitialDirectory = ("E:");
            saveFileDialog1.Title = "Save as Excel File";
            saveFileDialog1.FileName = "";
            saveFileDialog1.Filter = "Excel Files(2003)|*.xls| Excel Files(2007)|*.xlsx";

            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
            {
                Excel.Application ExcelApp = new Excel.Application();
                ExcelApp.Application.Workbooks.Add(Type.Missing);
                ExcelApp.Columns.AutoFit();
                Excel.Worksheet sheet = ExcelApp.ActiveSheet;
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    sheet.Cells[1, i+1] = dataGridView1.Columns[i].HeaderText;
                }

                for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        sheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    
                }
                MessageBox.Show("Data Exported Successfully");
                sheet.SaveAs(saveFileDialog1.FileName);
                ExcelApp.Visible = true;
                ExcelApp.Quit();
                
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM