C# et Excel

http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
 
ex venant d'un autre site:
 
using System;
using System.Runtime.InteropServices;

namespace WriteToExcel
{
    class Program
    {
        const string EXCEL_PROG_ID = "Excel.Application";

        const uint MK_E_UNAVAILABLE = 0x800401e3;

        const uint DV_E_FORMATETC = 0x80040064;

        static void Main(string[] args)
        {
            dynamic excelApp = null;
            try
            {
                excelApp = Marshal.GetActiveObject(EXCEL_PROG_ID);
            }
            catch (COMException ex)
            {
                switch ((uint)ex.ErrorCode)
                {
                    case MK_E_UNAVAILABLE:
                    case DV_E_FORMATETC:
                        // Excel n'est pas lancé.
                        break;

                    default:
                        throw;
                }
            }

            if (null == excelApp)
                excelApp = Activator.CreateInstance(Type.GetTypeFromProgID(EXCEL_PROG_ID));

            if (null == excelApp)
            {
                Console.Write("Unable to start Excel");
                return;
            }

            excelApp.Visible = true;

            dynamic workbook = excelApp.ActiveWorkbook ?? excelApp.Workbooks.Add();
            dynamic sheet = workbook.ActiveSheet;
            dynamic cell = sheet.Cells[1, 1];
            cell.Value = "Hello world!";
        }
    }
________________________________________________ 
 
 

using System.IO;
using OfficeOpenXml;
namespace NPOITest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            FileStream fs = new FileStream("test.xlsx", FileMode.Create);
            ExcelPackage package = new ExcelPackage(fs);
            ExcelWorksheet wSheet = package.Workbook.Worksheets.Add("Test");
            wSheet.Cells[5, 1].Value = 77;
             
            package.Save();
            package.Dispose();
            fs.Close();
        }
    }
}
 ________________________________________________________________
http://skalp.developpez.com/tutoriels/csharp/automationexcel/
_______________________________________________________________
static public void ExportToExcel(String file, 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++)
                    {
                        // Afin de configurer la cellule en mode texte
                        String text = "'" + dt.Rows[y].ItemArray[i].ToString();
                        ((Excel.Range)xlSheet.Cells[y + 2, i + 1]).Value2 = text;
                    }
                }
            }
            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;
 
                            // Afin de configurer la cellule en mode texte
                            String text = "'" + dt.Rows[y + (nb * UInt16.MaxValue)].ItemArray[i].ToString();
                            ((Excel.Range)xlSheet.Cells[y + 2, i + 1]).Value2 = text;
                        }
                    }
                }
            }
 
            // 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;
        }
    }
}
 
 ______________________________________________________________
 
' sur autre exple:    using System;
' suivi de            using System.Runtime.InteropServices;
 
'ouvrir un fichier Excel via C#, y ajouter des données,
' puis fermer en enregistrant (sans écraser les précédentes donnée) 
 
        Microsoft.Office.Interop.Excel.Application appli;
        Microsoft.Office.Interop.Excel._Workbook classeur;
        Microsoft.Office.Interop.Excel._Worksheet feuille;
        object M = System.Reflection.Missing.Value;
        object FileName = "c:\\MonFichierExcel.xls";
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                appli = new Microsoft.Office.Interop.Excel.Application();
                appli.Visible = false;
 
                //---------- création du classeur ---------
                classeur = (Microsoft.Office.Interop.Excel._Workbook)(appli.Workbooks.Open("c:\\MonFichierExcel.xls", M, M, M, M, M, M, M, M, M, M, M, M, M, M));
                //------ activer la feuille ----------
                feuille = (Microsoft.Office.Interop.Excel._Worksheet)classeur.ActiveSheet;
 
                //Remplir les en-têtes
                feuille.Name = "Entete Quitance";
                feuille.Cells[1, 1] = "Nom";
                feuille.Cells[1, 2] = "Prénom";
                feuille.Cells[1, 3] = "Age";
 
 
 
                //----- Auto-Enregistrement ---------------
               ' écrase fichier: classeur.Close(true, FileName, M);
               ' n'écrase pas
                classeur.Close(true, M, M); // M représenter "Missing Value"
 
 }
            catch (Exception ex) { MessageBox.Show("erruer est: " + ex.Message); }
            finally
            {
                //----- Quitter ------
                feuille = null;
                classeur = null;
                appli.Quit();
                appli = null;
            }
        }
 
 ________________________
 
using Microsoft.Office.Interop.Excel;


 public Microsoft.Office.Interop.Excel.ApplicationClass oExcelApp;
        public Microsoft.Office.Interop.Excel.Workbooks oBooks;
        public Microsoft.Office.Interop.Excel.Workbook oBook;
        public Microsoft.Office.Interop.Excel.Worksheet oSheet;
        public void ExportVersExcel()
        {
            oExcelApp = null;
            oBooks = null;
            oBook = null;
            oSheet = null;
             // Créer l’objet Excel             oExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
            oExcelApp.Visible = true; // l’afficher  ou pas
            oBooks = oExcelApp.Workbooks; 
            //ouvrir le fichier Excel désiré 
            oBook = oBooks.Open(nomfichier, Missing.Value ,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value,Missing.Value);
           // on active la feuille            oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oExcelApp.ActiveSheet;
            // on active la feuille auto            oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oExcelApp.Sheets.get_Item("auto");
             // lancement d' une macro            object ret = oExcelApp.Application.Run("macro1", Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value, Missing.Value);
             ///trouver la fin du fichier (bricolage, faut pas qu'il y ai des cases vides)int i =1 ;
                        while (oSheet.get_Range("A" + i, "A" + i).Text != "")
                                {
                                    i++;
                                }
                    //ecrire dans le fichier                        oSheet.Cells.Cells[i, 1] = dateCommande;
//fermeture Propre d'excel
 oBook.Save();
            if (oBook != null) { oBook.Close(true, nomfichier, Missing.Value); }
            if (oSheet != null) {System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet); 
            oSheet = null; }
            if (oBook != null) {System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook) ;
            oBook = null; }
            if (oBooks != null) {System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks) ;
            oBooks = null; }
            if (oExcelApp != null) 
            { 
            oExcelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp); oExcelApp = null;
 
  
_____________________
J'utilise Microsoft Visual Studio .NET 2008 pour programmer en C#. 

Je suis débutant et cherche a créer un fichier .xls avec mon application.

J'ai ajouté ma référence Microsoft.Office.Interop.Excel.

Mais je ne trouve pas comment créer le fichier excel.
-> 
au lieu de Workbooks.Open(), tu fais Workbooks.Add().
 
 
__________________________________
http://skalp.developpez.com/tutoriels/csharp/automationexcel/
 
 
 
 

Aucun commentaire:

Enregistrer un commentaire