I am exporting data from a datagridview to an excel

0

I need to export the data that I am entering in the datagrid to an excel but it gives me the following error Exception of HRESULT: 0x800AC472

The code is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace Boletin7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btguardarexcel_Click(object sender, EventArgs e)
        {
            Excel.Application objExcel = new Excel.Application();
            objExcel.Visible = true; //Podríamos trabajar sin que se vea…
            Excel.Workbook objLibro = objExcel.Workbooks.Add(Missing.Value);
            Excel.Worksheet objHoja =
           (Excel.Worksheet)objLibro.Worksheets.get_Item(1); //hoja 1

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

            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                for (int j = 0; i < dataGridView2.Columns.Count; j++)
                {
                    objHoja.Cells[i+2, j+1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
                }
            }

            var saveFileDialoge = new SaveFileDialog();
            saveFileDialoge.FileName = "output";
            saveFileDialoge.DefaultExt = ".xlsx";

            if(saveFileDialoge.ShowDialog()==DialogResult.OK)
            {
                objLibro.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }



        }

        private void btSalirexcel_Click(object sender, EventArgs e)
        {
            DialogResult salir = MessageBox.Show("Seguro?", "Salir", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (salir == DialogResult.Yes)
            {
                Close();
            }
        }
    }
}

If someone could help me with this case I would be very grateful, Thank you very much in advance. The bug is here objHoja.Cells[i,1] = dataGridView2.Columns[i - 1].HeaderText;

    
asked by El Barto 29.04.2018 в 19:57
source

0 answers