Ouvrir et lire un fichier Excel à partir d’une application C# WPF

Petit tutoriel qui permet d’ouvrir et de lire les valeurs d’un fichier Excel à partir d’une application C# WPF. Cette manipulation vous donnera la possibilité d’afficher ces données à l’écran, de les insérer dans une base de données, etc…

Ajout d’une référence, quelques lignes de code et le tour est joué.

Etape 1 : Ajout de la référence au projet

Pour commencer, il faut ajouter la référence Excel à votre projet C#.

  • Faites un clic droit sur votre projet
  • Cliquez sur “Ajouter une référence…”
  • Sélectionnez l’onglet “COM”
  • Cherchez “Microsoft Excel XX.X Object Library” (voir ci-dessous)

excel_object_library

Vous devriez voir apparaître la référence (dans le volet de droite), une référence appelée “Microsoft.Office.Interop.Excel” :

interop_excel

Etape 2 : Ajout de la référence dans le code

A ajouter dans la partie “directive” du code de votre form ou classe (tout en haut) :

[csharp]using Excel = Microsoft.Office.Interop.Excel;[/csharp]

Etape 3 : Ajout des méthodes d’ouverture/lecture

Pour ouvrir l’explorateur de fichiers windows, sélectionner un fichier, l’ouvrir et lire les données qu’il contient, il faut ajouter les deux méthodes ci-dessous :

[csharp]private void OuvertureLectureXLS()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;

string str;
int rCnt = 0;
int cCnt = 0;
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Filter = "Excel files (*.xls*)|*.xls*;";
OpenFileDialog1.ShowDialog();
if (OpenFileDialog1.FileName != String.Empty)
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(OpenFileDialog1.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
cCnt = 1;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
str = Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2);
MessageBox.Show(str);
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
[/csharp]

Maintenant il ne vous reste plus qu’à appeler la méthode “OuvertureLectureXLS()” à partir du clic d’un bouton ou autre…

36 Comments Ouvrir et lire un fichier Excel à partir d’une application C# WPF

  1. 918kiss-m.com

    I don’t even know the way I finished up here, but I
    believed this submit used to be good. I don’t recognize who
    you might be but certainly you’re going to a
    famous blogger in case you are not already. Cheers!

    Feel free to surf to my web-site – game slot 918kiss 2 – 918kiss-m.com,

    Reply
  2. Joker123 via pulsa 10rb

    Saya telah telah berselancar online lebih dari 2 jam hari
    ini, namun saya tidak pernah menemukan artikel menarik seperti milik Anda.
    It is cukup berharga bagi saya. Dalam pandangan saya, jika semua pemilik situs
    dan blogger membuat konten yang baik seperti yang Anda lakukan, web akan menjadi lebih berguna
    dari sebelumnya.

    Also visit my blog post – Joker123 via pulsa 10rb

    Reply
  3. liga178.id

    Ηell there! This post could not be written mսch better!
    Going thrοugh this article гemіndѕ me of my prevіous roommate!

    He always kept talқing aboutt tһis. I am ɡoing to fоrward tһis post to
    him. Faidly certaіn he ѡill have a greаt гead. Many thanks for
    sharing!

    Reply
  4. 파워볼분석

    My partner and I stumbled over here coming from a different web address and thought I may as well check things out.

    I like what I see so i am just following you. Look
    forward to finding out about your web page yet again.

    Reply
  5. Tia

    What’s up, this weekend is good in support of me, since this moment
    i am reading this fantastic educational piece of writing here at my residence.

    Here is my webpage: ntc33 original (Tia)

    Reply
  6. www.nav-bookmarks.win

    I blog often and I realy thank yօu for your information. This article has truly peaked my
    interest. I will bookmark your blog and keep checking fοr new informmation about once per
    week. I subscribed to your Feed too.

    Reply
  7. wm casino online

    Unquestionably believe that which you said. Your favorite reason appeared to
    be on the internet the simplest thing to be aware of. I say to you,
    I definitely get irked while people think about worries that they plainly do not know about.
    You managed to hit the nail upon the top and also defined out the
    whole thing without having side effect , people can take a signal.
    Will probably be back to get more. Thanks

    Also visit my web blog – wm casino online

    Reply
  8. Beatris

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this
    for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

    Reply
  9. Geraldo

    We’re a gaggle of volunteers and starting a new scheme in our community.
    Your website provided us with helpful information to work on. You’ve performed a formidable process and our whole group might be grateful to you.

    Reply

Leave a Reply to Uefa Champions league Cancel reply

Your email address will not be published.