[C#][Excel] Problème pour écrire dans une cellule
Bonjour,
J'ai créer une méthode statique qui permet d'exporter une dataTable dans un fichier Excel.
Cette méthode fonctionne très bien sauf dans un cas, lorsque le texte à écrire commence par =, l'application plante et j'obtiens le message d'erreur :
Citation:
Exception de HRESULT : 0x800A03EC
Voici le code ma méthode.
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| static public void ExportToExcel(String file, System.Data.DataTable dt)
{
Excel.Application xlApp = null;
Excel.Workbook xlBook;
Excel.Worksheet xlSheet;
try
{
if (dt != null)
{
xlApp = new Excel.Application();
if (xlApp == null)
{
throw new Exception("ERROR: EXCEL couldn't be started");
}
String newFile = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file) + "_" + DateTime.Now.ToShortDateString().Replace("/", "") + ".xls");
xlApp.Visible = false;
object missing = Missing.Value;
xlBook = xlApp.Workbooks.Add(missing);
xlSheet = (Excel.Worksheet)xlBook.ActiveSheet;
// On vérifie qu'il n'y a pas plus de 65535 lignes
if (dt.Rows.Count < UInt16.MaxValue)
{
/* Importation des données */
// Création des colonnes
for (int i = 0; i < dt.Columns.Count; i++)
{
xlSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
// Remplissage du contenu
for (int y = 0; y < dt.Rows.Count; y++)
{
((Range)xlSheet.Cells[y + 2, i + 1]).Value2 = dt.Rows[y].ItemArray[i].ToString();
}
}
}
else
{
// Nombre de feuilles Excel
int nbSheet = dt.Rows.Count / UInt16.MaxValue;
if (dt.Rows.Count % UInt16.MaxValue > 0)
nbSheet++;
for (int i = xlBook.Sheets.Count; i <= nbSheet; i++)
{
xlBook.Sheets.Add(missing, missing, missing, missing);
}
for (int nb = 0; nb < nbSheet; nb++)
{
xlSheet = (Excel.Worksheet)xlBook.Sheets[nb + 1];
xlSheet.Name = dt.TableName + "_" + (nb + 1);
for (int i = 0; i < dt.Columns.Count; i++)
{
xlSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
// Remplissage du contenu
for (int y = 0; y < UInt16.MaxValue; y++)
{
// On teste la fin de la DataTable
if (y + (nb * UInt16.MaxValue) >= dt.Rows.Count)
break;
xlSheet.Cells[y + 2, i + 1] = dt.Rows[y + (nb * UInt16.MaxValue)].ItemArray[i].ToString();
}
}
}
}
// Sauvegarde du fichier
xlSheet.SaveAs(newFile, missing, missing, missing, missing, missing, missing, missing, missing, missing);
}
else
throw new Exception("Aucune donnée à afficher dans Excel");
}
catch (Exception e)
{
throw e;
}
finally
{
if (dt != null)
{
xlApp.Quit();
xlSheet = null;
xlBook = null;
xlApp = null;
}
}
} |
Est ce que quelqu'un a déjà rencontré ce problème ?
Merci par avance.
Mosco