mgf mgf

mgf mgf

  • NA
  • 10
  • 481

Excel et listview

Mar 25 2023 9:19 PM

Bonjour

J'ai un  probleme d'affichage d'un fichier excel  sur deux listview en fonction de la parité de la ligne.

jusque là tout va bien mais l'affichage pose proble car , il l'affiche mais un peu n'impote comment.

voici mon code: 

using System.Data;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Excel = Microsoft.Office.Interop.Excel;

namespace E14_Cours_3;

public partial class Form1 : Form
{
    public static Excel.Application? excelApp;
    public static Excel.Workbook? excelBook;
    public static Excel.Worksheet? excelSheet;
    public static Excel.Range? excelRange;
    private StreamingContext j;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = new Excel.Application();

        if (excelApp == null)
        {
            MessageBox.Show("Désolé, cette application nécessite Excel. Veuillez l'installer et réessayer.");

            Application.Exit();
        }
        else
        {
            try
            {
                excelBook = excelApp.Workbooks.Open(AppContext.BaseDirectory + "Test.xlsx");

                excelSheet = excelBook.Worksheets[1];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Une erreur s'est produite.");

                Application.Exit();
            }
        }

    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        excelApp!.Quit();

        GC.WaitForPendingFinalizers();

        GC.Collect();

    }

    private void btnLireExcel_Click(object sender, EventArgs e)
    {

        int lastRow = excelSheet!.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;

        int lastCol = excelSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Column;

        //MessageBox.Show("le nombre de ligne: " + lastRow + " nombre colonne: " + lastCol);

        for (int i = 1; i <= lastRow; i++)

        {
            Excel.Range RowRange = excelSheet.Rows[i];

            string[] rowData = new string[lastCol];

            //Recuperer les données de la ligne 

            for (int j = 1; j <= lastCol; j++)
            {
                Excel.Range cell = RowRange.Cells[j];

                if (cell.Value != null)
                {
                    rowData[j - 1] = cell.Value.ToString();
                }

            }

            

            ListViewItem item = new ListViewItem(rowData);

            //Ajout de l'élément en fonction de la parité de la ligne

            if (i % 2 == 0)
            {
                LVCourse.Items.Add(item);

            }
            else
            {
                LVPatineur.Items.Add(item);
            }
        }

        
    }
}

Merci


Answers (3)