Transférer les données d'un DataGridView dans un fichier Excel

Résolu
cs_warzet Messages postés 99 Date d'inscription jeudi 17 janvier 2008 Statut Membre Dernière intervention 25 juillet 2013 - 25 juin 2012 à 09:12
cs_warzet Messages postés 99 Date d'inscription jeudi 17 janvier 2008 Statut Membre Dernière intervention 25 juillet 2013 - 13 août 2012 à 09:32
Bonjour à tous,
j'ai un gros soucis, et je sollicite votre aide en cela. J'ai un DataGridView et je souhaiterais en transférer les données dans un fichier Excel pour impression: par votre aide, j'ai fait ceci.
[using System.Reflection;
using ExcelApplication = Microsoft.Office.Interop.Excel.Application;
]
[ #region DECLARATION
private string UnFichier = "Bulletin.xls";
private string NomEntete = "Notation";
#endregion
]
[#region ExporterGridVersExcel Surchargé Type #1
///<summary>
///Permet d'exporter un DataGrid vers excel
///</summary>
/// Data Grid Source des données à Exporter vers Excel


///Fichier Excel de destination des données


///Libellé de l'en-tête du fichier à générer


public void ExporterGridVersExcel(DataGridView dgView, String unFichier, string strEnteteDeFichier)
{
int i = 0;
int j = 0;
ExcelApplication excel = new ExcelApplication();
Microsoft.Office.Interop.Excel.Workbook exbook = (Microsoft.Office.Interop.Excel.Workbook)excel.Workbooks.Add(Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet exsheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;

try
{
//Mise en forme de l'en-tête de la feuille Excel
exsheet.Cells[1, 1] = strEnteteDeFichier;
Microsoft.Office.Interop.Excel.Range r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value);
r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
r.Font.Bold = true;
r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
r.EntireColumn.AutoFit();//Fin de la mise en forme de l'en-tête.

foreach (DataGridViewColumn ch in dgView.Columns)
{
if (exsheet.Cells[j, i] != null)
{
r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value);
exsheet.Cells[2, i + 1] = ch.Name.Trim();
r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
r.Font.Bold = true;
r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
r.EntireColumn.AutoFit();
i++;
}
}
j = 3;

foreach (DataGridViewRow uneLigne in dgView.Rows)
{
i = 1;
foreach (DataGridViewColumn uneColonne in dgView.Columns)
{
if (exsheet.Cells[j, i] != null)
{
r = exsheet.get_Range(Convert.ToChar(65 + i - 1).ToString() + j.ToString(), Missing.Value);
exsheet.Cells[j, i] = "'" + uneLigne.Cells[uneColonne.Name].Value.ToString().Trim();
r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
r.EntireColumn.AutoFit();
i++;
}
}
exsheet.Columns.AutoFit();
j++;
}
exsheet.SaveAs(unFichier, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
excel.Quit();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
excel.Quit();
}
}

#endregion]

[ private void btnExcel_Click(object sender, EventArgs e)
{
ExporterGridVersExcel(dgvMoyenne,UnFichier,NomEntete);
}
]

Mais j'obtiens l'erreur suivante:

[Impossible d'effectuer un cast d'un objet COM de type 'Microsoft.Office.Interop.Excel.ApplicationClass' en type d'interface 'Microsoft.Office.Interop.Excel._Application'. Cette opération a échoué, car l'appel QueryInterface sur le composant COM pour l'interface avec l'IID '{000208D5-0000-0000-C000-000000000046}' a échoué en raison de l'erreur suivante : n’a pas pu être trouvé. (Exception de HRESULT : 0x80030002 (STG_E_FILENOTFOUND)).]/quote

Quelqu'un peut-il me dire d'où me provient cette erreur?
Merci beaucoup à tous.

25 réponses

Whismeril Messages postés 19021 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 16 avril 2024 656
11 juil. 2012 à 13:06
j'ai viré le
using ExcelApplication = Microsoft.Office.Interop.Excel.Application;

ce code fonctionne pour moi
        public void ExporterGridVersExcel(DataGridView dgView, String unFichier, string strEnteteDeFichier)
        {
            int i = 0;
            int j = 0;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//ici je déclare direct excel
            Microsoft.Office.Interop.Excel.Workbook exbook = (Microsoft.Office.Interop.Excel.Workbook)excel.Workbooks.Add(Missing.Value);
            Microsoft.Office.Interop.Excel.Worksheet exsheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
            excel.Visible = true;

            //try
            //{
                //Mise en forme de l'en-tête de la feuille Excel 
                exsheet.Cells[1, 1] = strEnteteDeFichier;
                Microsoft.Office.Interop.Excel.Range r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value);
                r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
                r.Font.Bold = true;
                r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
                r.EntireColumn.AutoFit();//Fin de la mise en forme de l'en-tête. 

                foreach (DataGridViewColumn ch in dgView.Columns)
                {
                    if (exsheet.Cells[2, 2] != null)
                    {
                        r = exsheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value);
                        exsheet.Cells[2, i + 1] = ch.Name.Trim();
                        r.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
                        r.Font.Bold = true;
                        r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
                        r.EntireColumn.AutoFit();
                        i++;
                    }
                }
                j = 3;

                foreach (DataGridViewRow uneLigne in dgView.Rows)
                {
                    i = 1;
                    foreach (DataGridViewColumn uneColonne in dgView.Columns)
                    {
                        if (exsheet.Cells[j, i] != null)
                        {
                            r = exsheet.get_Range(Convert.ToChar(65 + i - 1).ToString() + j.ToString(), Missing.Value);
                            if (uneLigne.Cells[uneColonne.Name].Value != null) exsheet.Cells[j, i] = "'" + uneLigne.Cells[uneColonne.Name].Value.ToString().Trim();

                            r.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
                            r.EntireColumn.AutoFit();
                            i++;
                        }
                    }
                    exsheet.Columns.AutoFit();
                    j++;
                }
                exsheet.SaveAs(unFichier, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                //excel.Quit();
            //}
            //catch (Exception ex)
            //{
            //    throw (ex);
            //}
            //finally
            //{
                //excel.Quit();
            //}
        }



Whismeril
0
cs_warzet Messages postés 99 Date d'inscription jeudi 17 janvier 2008 Statut Membre Dernière intervention 25 juillet 2013 1
13 juil. 2012 à 09:06
Merci pour ton code, je vais l'essayer.
0
Rapakooti Messages postés 90 Date d'inscription mercredi 4 décembre 2002 Statut Membre Dernière intervention 18 mai 2018
19 juil. 2012 à 08:56
Bonjour, j'ai une question vraiment bete, est ce que le poste qui execute le code doit forcement avoir excel d'installer? C est limitant non?

R A P A K O O T I
0
Whismeril Messages postés 19021 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 16 avril 2024 656
19 juil. 2012 à 10:10
@Rapakooti, oui il faut excel pour ce code.


Whismeril
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
cs_warzet Messages postés 99 Date d'inscription jeudi 17 janvier 2008 Statut Membre Dernière intervention 25 juillet 2013 1
13 août 2012 à 09:32
Bonjour à tous,
Le code fonctionne normalement, il me fallait réinstaller mon Office qui présentait des anomalies. Mercis
0
Rejoignez-nous