SoFunction
Updated on 2025-03-07

c# Use Excel to directly read data to DataGridView


using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using Excel=;
using ;
using ;

 
namespace Excelproject
{
    public partial class ExcelForm : Form
    {

        private ExcelOperate eo;
        private string excelpath;
        private excel1;
        private wbs = null;
        private wb = null;
        private   wss;
        private ws = null;
        private range1 = null;

 
        public ExcelForm()
        {
            InitializeComponent();
            this.excel1 = new ();
            if (excel1 == null)
            {
                ("error");
                ();
            }
             = true;

        }

 

#region excel file opening and closing operation
private void Open _Click(object sender, EventArgs e)
        {
            openFileDialog1 = new OpenFileDialog();
= "Open excel file";
= "excel03 file (*.xls)|*.xls|excel07 file (*.xlsx)|*.xlsx";
             = @"C:\Users\Administrator\Desktop";
             = true;
            if (() == )
            {
//Open the file selected by the file dialog box
                excelpath = ;
                eo = new ExcelOperate();
                readExcel(excelpath);

            }
        }

        void readExcel(string path)
        {
            object miss = ;
             = true;
             = false;
            (excelpath, miss, miss, miss, miss,
                                             miss, miss, miss, miss,
                                             miss, miss, miss, miss,
                                             miss, miss);
            wbs = ;
            wss = wbs[1].Worksheets;
            ws = () wss.get_Item(1);
            int rowNum = ;
            int colNum = ;
            string cellStr = null;
            char ch = 'A';
            for (int i = 0; i < colNum; i++)
            {
                ((), ());
                (rowNum);
                for (int j = 0; j <rowNum; j++)
                {
                    cellStr = () + (j + 1).ToString();
                    dataGridView1[i, j].Value = .get_Range(cellStr, miss).();
                }
                ch++;
            }

 
        }

        #endregion

    }
}