Problème d'export de datagridview vers excel
Bonsoir tout le monde !
Cette fois-ci j'ai essayé d'exporter une datagridview vers excel.
Le programme fonctionne lorsque le tableau que je dois transférer ne dépasse pas 26 colonnes.
En effet j'ai un problème quand les colonnes d'excel passent à AA, AB, AC .. et je ne vois pas d'où provient le problème !
Je poste ici la boucle qui me sert à transférer mon datagridview :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| private void button3_Click(object sender3, EventArgs e3)
{
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
// Copier les noms des colonnes
int i=0;
foreach (DataGridViewColumn ch in dataGridView2.Columns)
{
oRng = oSheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", Missing.Value);
oSheet.Cells[1, i + 1] = ch.Name.Trim();
oRng.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
oRng.Font.Bold = true;
oRng.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
oRng.EntireColumn.AutoFit();
i++;
}
// Copier toutes les cellules du datagridview1
// j=3 on commence à la 3eme ligne dans le fichier excel
int j = 3;
foreach (DataGridViewRow uneLigne in dataGridView2.Rows)
{
i = 1; // si i=1 alors 65-1+1 donne 65<=>A et ainsi on aura la lettre de la colonne puis on juxtapose le numero de la ligne
foreach (DataGridViewColumn uneColonne in dataGridView2.Columns)
{
oRng = oSheet.get_Range(Convert.ToChar(65 + i - 1).ToString() + j.ToString(), Missing.Value);
oSheet.Cells[j, i] = uneLigne.Cells[uneColonne.Name].Value.ToString().Trim();
oRng.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, Missing.Value);
oRng.EntireColumn.AutoFit();
i++;
}
oSheet.Columns.AutoFit();
j++;
}
}
catch(Exception ex)
{
MessageBox.Show("Erreur est: " + ex.Message,"Erreur");
}
} |
J'espère que vous pourrez m'apporter quelques indices !