Tuesday, June 16, 2020

Read a cell from an excel sheet using CSharp

Create a windows form project,add a com reference named Microsoft Excel 16.0 Object Library

Create a Class named Excel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
namespace chsarpexcelpart1
{
    class Excel
    {
        string path = "";
        _Application excel = new _Excel.Application();
        Workbook wb;
        Worksheet ws;
        public Excel(string path, int Sheet)
        {
            this.path = path;
            wb = excel.Workbooks.Open(path);
            ws = wb.Worksheets[Sheet];

        }
        public string ReadCell(int i, int j)
        {
            i++;
            j++;
            if (ws.Cells[i, j].Value2 != null)
                return ws.Cells[i, j].value2;
            else
                return "";

        }
        public void Close()
        {
            wb.Close();

        }
    }
}

Now go to the form code

private void Form1_Load(object sender, EventArgs e)
        {
            OpenFile();
        }
        public void OpenFile()
        {
            Excel excel = new Excel(@"C:\Users\allso\source\repos\chsarpexcelpart1\chsarpexcelpart1\Test.xlsx", 1);
            MessageBox.Show(excel.ReadCell(0, 0));
excel.Close();
        }


No comments:

Post a Comment