Office interop excel open file

I am trying to convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work?

Excel.Application objexcel;
Excel.Workbook wbexcel;
bool wbexists;
Excel.Worksheet objsht;
Excel.Range objrange;

objexcel = new Excel.Application();
if (Directory("C:\csharp\error report1.xls") = "")
{
    wbexcel.NewSheet();
}

else
{
    wbexcel.Open("C:\csharp\error report1.xls");
    objsht = ("sheet1");
}
objsht.Activate();

abatishchev's user avatar

abatishchev

97.3k85 gold badges297 silver badges432 bronze badges

asked Jan 21, 2009 at 11:25

tksy's user avatar

4

You need to have installed Microsoft Visual Studio Tools for Office (VSTO).

VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.

After that create a generic .NET project and add a reference to Microsoft.Office.Interop.Excel via ‘Add Reference… > Assemblies’ dialog.

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);

Missing.Value is a special reflection struct for unnecessary parameters replacement


In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.

enter image description here

answered Jan 21, 2009 at 15:07

abatishchev's user avatar

abatishchevabatishchev

97.3k85 gold badges297 silver badges432 bronze badges

13

FileInfo fi = new FileInfo("C:\test\report.xlsx");
if(fi.Exists)
{
    System.Diagnostics.Process.Start(@"C:testreport.xlsx");
}
else
{
    //file doesn't exist
}

Community's user avatar

answered Oct 18, 2011 at 21:49

Mennan's user avatar

MennanMennan

4,42112 gold badges53 silver badges86 bronze badges

4

private void btnChoose2_Click(object sender, EventArgs e)
{
  OpenFileDialog openfileDialog1 = new OpenFileDialog();
  if (openfileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {
    this.btnChoose2.Text = openfileDialog1.FileName;
    String filename = DialogResult.ToString();

    var excelApp = new Excel.Application();
    excelApp.Visible = true;
    excelApp.Workbooks.Open(btnChoose2.Text);
  }
}

LarsTech's user avatar

LarsTech

80.3k14 gold badges151 silver badges222 bronze badges

answered Jan 28, 2014 at 17:45

Flane's user avatar

FlaneFlane

1111 silver badge3 bronze badges

1

Imports

 using Excel= Microsoft.Office.Interop.Excel;
 using Microsoft.VisualStudio.Tools.Applications.Runtime;

Here is the code to open an excel sheet using C#.

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\YourExcelSheet.xlsx");
    Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

    wbv.Close(true, Type.Missing, Type.Missing);
    excel.Quit();

Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4

answered Aug 20, 2016 at 0:39

user1848210's user avatar

0

For opening a file, try this:

objexcel.Workbooks.Open(@"C:YourPathYourExcelFile.xls",
    missing, missing, missing, missing, missing, missing, missing,
    missing, missing, missing, missing, missing,missing, missing);

You must supply those stupid looking ‘missing’ arguments. If you were writing the same code in VB.Net you wouldn’t have needed them, but you can’t avoid them in C#.

answered Jan 21, 2009 at 11:39

Frederick The Fool's user avatar

2

you should open like this

        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 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);

source : http://csharp.net-informations.com/excel/csharp-open-excel.htm

ruden

answered Apr 17, 2013 at 6:23

rudenaggar's user avatar

0

It’s easier to help you if you say what’s wrong as well, or what fails when you run it.

But from a quick glance you’ve confused a few things.

The following doesn’t work because of a couple of issues.

if (Directory("C:\csharp\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won’t work since 1/ you don’t have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\csharp\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn’t work, you have to check the documentation for the Excel library which google should be able to provide for you.

answered Jan 21, 2009 at 14:57

Mats Fredriksson's user avatar

Mats FredrikssonMats Fredriksson

19.6k6 gold badges36 silver badges57 bronze badges

Microsoft.Office.Interop.Excel.Application excapp;

excapp = new Microsoft.Office.Interop.Excel.Application();

object misval=System.Reflection.Missing.Value;

Workbook wrkbuk = new Workbook();

Worksheet wrksht = new Worksheet();

wrkbuk = excapp.Workbooks._Open(@"C:Users......_template_v1.0.xlsx", misval, misval, 
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);

wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);

RememberME's user avatar

RememberME

2,0823 gold badges37 silver badges62 bronze badges

answered Jul 15, 2011 at 10:50

Jairaj's user avatar

Is this a commercial application or some hobbyist / open source software?

I’m asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain’t free.

answered Jan 21, 2009 at 15:29

Tamas Czinege's user avatar

Tamas CzinegeTamas Czinege

118k40 gold badges148 silver badges175 bronze badges

Code :

 private void button1_Click(object sender, EventArgs e)
     {

        textBox1.Enabled=false;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excell File |*.xlsx;*,xlsx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string extn = Path.GetExtension(ofd.FileName);
                if (extn.Equals(".xls") || extn.Equals(".xlsx"))
                {
                    filename = ofd.FileName;

                    if (filename != "")
                    {
                        try
                        {
                            string excelfilename = Path.GetFileName(filename);


                        }
                        catch (Exception ew)
                        {
                            MessageBox.Show("Errror:" + ew.ToString());
                        }
                    }
                }
            }

Dharmesh Porwal's user avatar

answered Jan 12, 2015 at 6:54

Gaurav Bari's user avatar

For editing Excel files from within a C# application, I recently started using NPOI.
I’m very satisfied with it.

Janus Troelsen's user avatar

answered Apr 4, 2012 at 15:06

bvgheluwe's user avatar

bvgheluwebvgheluwe

8537 silver badges25 bronze badges

  • Remove From My Forums
  • Question

  • Hi,

    I want to write a program to access cells in an excel file?

    How can I do that?

    Thanks

Answers

  • Try this code!

    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open("your excel file path", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet sheet = (Worksheet)wb.Sheets["Sheet name to read"]; Range excelRange = sheet.UsedRange; foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows) { int rowNumber = row.Row; string[] A4D4 = GetRange("A" + rowNumber + ":F" + rowNumber + "", sheet); } public string[] GetRange(string range, Worksheet excelWorksheet) { Microsoft.Office.Interop.Excel.Range workingRangeCells = excelWorksheet.get_Range(range, Type.Missing); //workingRangeCells.Select(); System.Array array = (System.Array)workingRangeCells.Cells.Value2; string[] arrayS = this.ConvertToStringArray(array); return arrayS; }


    • Edited by

      Monday, September 5, 2011 6:40 AM

    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:49 AM

  • Hi DarkSeeker,

    Try this:

    static void Main(string[] args)
    {
      IWorkbook workbook = Factory.GetWorkbook(@"C:tmpMyWorkbook.xls");
      IWorksheet worksheet = workbook.Worksheets[0];                 
      IRange a1 = worksheet.Cells["A1"]; 
      object rawValue = a1.Value;    
      string formattedText = a1.Text;             
      Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);         
    } 

    Regards, http://shwetamannjain.blogspot.com

    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:50 AM

  • I
    want to write a program to access cells in an excel file?

    Thanks all for your great help and suggestions.

    Hi DarkSeeker,

    Welcome to MSDN Forum.

    Usually, there are 2 approaches to access Office Excel files in .Net.

    1.      
    COM Interop approach as the above said.

    FAQ:  How do I use Excel Automation in .NET

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/df02c6d2-e1b5-4731-bb04-2674aed789de

    Add Reference to COM component “Microsoft Excel Object Library” into your project.

    Code sample: Get/Set cell value in Excel Spreadsheet.

    using Microsoft.Office.Interop.Excel;

    object oExcel
    = new Excel.Application;

    object oBook
    = oExcel.Workbooks.Open(«C:\Book1.xls»);
    object
    oSheet =
    oBook.Worksheets(1);
    // e.g. Read value in A2 cell

    string cellValue
    = oSheet.Range(«A2»).Value;
    // e.g. Change value in A2 cell
    oSheet.Range(«A2»).Value
    = «»;
    oBook.SaveAs(«C:\Book1.xls»,
    true);
    oExcel.Quit();

    2.       OleDb Data Provider approach

    Retrieve Excel Sheet data and bind into DataGridView control, and then access particular cells via DataGridView.

    using System.Data;

    using System.Data.OleDb;


    OleDbConnection conn = new
    OleDb.OleDbConnection((«provider=Microsoft.Jet.OLEDB.4.0; »
    + («data source=C:\myData.xls; »
    + «Extended Properties=Excel 8.0;»)));
    // Select the data from Sheet1 of the workbook.
    OleDbDataAdapter ada = new
    OleDbDataAdapter(«select * from Sheet1$]», conn);
    DataSet ds = new
    DataSet();
    ada.Fill(ds);
    dataGridView1.DataSource
    = ds.Tables[0].DefaultView;
    conn.Close();

    // Access particular cells on DataGridView.

    DataGridView1(RowIndex, ColumnIndex)

    DataGridView1.Rows(RowIndex).Cells(ColumnIndex)


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Proposed as answer by
      Carmelo La Monica
      Tuesday, September 6, 2011 5:54 AM
    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:48 AM

Table of Contents

  • Background
  • Prerequisites
  • Source Code


Background

A few days ago we got a requirement to read Excel files and store those values in the SQL server database. So in this example, we’re going to show how to get the basic four import data such as Excel Work Book
Name, Worksheet Count in that Workbook, Name of the First Worksheet, and finally the value of the first cell in that worksheet.

Prerequisites

Kindly ensure you add the following DLL as shown in the below screenshot,

add

add

Namespace

using Excel = Microsoft.Office.Interop.Excel;

Source Code

C# Code

  1. protected void BtnGetExcelFileDetails_Click(object sender, EventArgs e)   
  2. {  
  3.   
  4.     try   
  5.     {  
  6.           
  7.         Excel.Application oExcel = new Excel.Application();  
  8.   
  9.           
  10.         string filepath = @ «D:TPMSUploaded_BoqRaveena_boq_From_Db.xlsx»;  
  11.   
  12.           
  13.         Excel.Workbook WB = oExcel.Workbooks.Open(filepath);  
  14.   
  15.   
  16.           
  17.         string ExcelWorkbookname = WB.Name;  
  18.   
  19.           
  20.         int worksheetcount = WB.Worksheets.Count;  
  21.   
  22.         Excel.Worksheet wks = (Excel.Worksheet) WB.Worksheets[1];  
  23.   
  24.           
  25.   
  26.         string firstworksheetname = wks.Name;  
  27.   
  28.           
  29.         var firstcellvalue = ((Excel.Range) wks.Cells[1, 1]).Value;  
  30.   
  31.     } catch (Exception ex)   
  32.     {  
  33.   
  34.         string error = ex.Message;  
  35.     }  
  36.   
  37. }  

Hope the above information was useful.

Все привет, в этой статье опишу исчерпывающие примеры работы с excel на языке C#.

Для начала работы нам необходимо подключить библиотеку COM как на рисунке ниже:

Для этого добавляем ссылку в проект, надеюсь вы знаете как это делается) Выбираем пункт COM ищем библиотеку Microsoft Excel 16.0 Object Library ставим галочку и жмем Ок.

Далее нам не обходимо для сокращения записи и удобства создать алиас.

using Excel = Microsoft.Office.Interop.Excel;

Теперь нам нужно объявить объект Excel задать параметры и приступать к работе.

//Объявляем приложение

            Excel.Application app = new Excel.Application

            {

                //Отобразить Excel

                Visible = true,

                //Количество листов в рабочей книге

                SheetsInNewWorkbook = 2

            };

            //Добавить рабочую книгу

            Excel.Workbook workBook = app.Workbooks.Add(Type.Missing);

            //Отключить отображение окон с сообщениями

            app.DisplayAlerts = false;

            //Получаем первый лист документа (счет начинается с 1)

            Excel.Worksheet sheet = (Excel.Worksheet)app.Worksheets.get_Item(1);

            //Название листа (вкладки снизу)

            sheet.Name = «Имя должно быть не больше 32сим»;

Пример заполнения ячейки:

           //Пример заполнения ячеек №1

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

            {

                for (int j = 1; j < 9; j++)

                    sheet.Cells[i, j] = String.Format(«nookery {0} {1}», i, j);

            }

            //Пример №2

            sheet.Range[«A1»].Value = «Пример №2»;

            //Пример №3

            sheet.get_Range(«A2»).Value2 = «Пример №3»;

Захват диапазона ячеек:

            //Захватываем диапазон ячеек Вариант №1

            Excel.Range r1 = sheet.Cells[1, 1];

            Excel.Range r2 = sheet.Cells[9, 9];

            Excel.Range range1 = sheet.get_Range(r1, r2);

            //Захватываем диапазон ячеек Вариант №2

            Excel.Range range2 = sheet.get_Range(«A1»,«H9» );

Оформление, шрифт, размер, цвет, толщина.

            //Шрифт для диапазона

              range.Cells.Font.Name = «Tahoma»;

              range2.Cells.Font.Name = «Times New Roman»;

            //Размер шрифта для диапазона

              range.Cells.Font.Size = 10;

            //Жирный текст

              range.Font.Bold = true;

            //Цвет текста

              range.Font.Color = ColorTranslator.ToOle(Color.Blue);

Объединение ячеек в одну

  //Объединение ячеек с F2 по K2

    Excel.Range range3 = sheet.get_Range(«F2», «K2»);

    range3.Merge(Type.Missing);

Изменяем размеры ячеек по ширине и высоте

//увеличиваем размер по ширине диапазон ячеек

   Excel.Range range2 = sheet.get_Range(«D1», «S1»);

   range2.EntireColumn.ColumnWidth = 10;

//увеличиваем размер по высоте диапазон ячеек

   Excel.Range rowHeight = sheet.get_Range(«A4», «S4»);

   rowHeight.EntireRow.RowHeight = 50;range.EntireColumn.AutoFit();range.EntireColumn.AutoFit(); //авторазмер

Создаем обводку диапазона ячеек

Excel.Range r1 = sheet.Cells[countRow, 2];

Excel.Range r2 = sheet.Cells[countRow, 19];

Excel.Range rangeColor = sheet.get_Range(r1, r2);

rangeColor.Borders.Color = ColorTranslator.ToOle(Color.Black);

Производим выравнивания содержимого диапазона ячеек.

  Excel.Range r = sheet.get_Range(«A1», «S40»);

  //Оформления

  r.Font.Name = «Calibri»;

  r.Cells.Font.Size = 10;

  r.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;

  r.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

Примеры вычисления формул, все вставки формул были скопированы из самой Excel без изменений. Позиция ячейки взята из счетчика переменно и подставлен к букве ячейки

sheet.Cells[countRow, countColumn] = $«=G{countRow}-F{countRow}»;

sheet.Cells[countRow, countColumn].FormulaLocal = $«=ЕСЛИ((H{countRow}*O{countRow})+(I{countRow}*P{countRow})/100<=0;J{countRow}*O{countRow}/100;((H{countRow}*O{countRow})+(I{countRow}*P{countRow}))/100)»;

sheet.Cells[countRow, countColumn] = $«=K{countRow}+N{countRow}-R{countRow}»;

sheet.Cells[33, 22].FormulaLocal = «=СУММ(V3:V32)»;

Добавляем разрыв страницы.

//Ячейка, с которой будет разрыв

Excel.Range razr = sheet.Cells&#91;n, m] as Excel.Range;

//Добавить горизонтальный разрыв (sheet — текущий лист)

sheet.HPageBreaks.Add(razr);

//VPageBreaks — Добавить вертикальный разрыв

Как открыть фаил Excel

app.Workbooks.Open(@»C:UsersUserDocumentsExcel.xlsx»,

  Type.Missing, Type.Missing, Type.Missing, Type.Missing,

  Type.Missing, Type.Missing, Type.Missing, Type.Missing,

  Type.Missing, Type.Missing, Type.Missing, Type.Missing,

  Type.Missing, Type.Missing);

Сохраняем документ Excel

app.Application.ActiveWorkbook.SaveAs(«MyFile.xlsx», Type.Missing,

  Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,

  Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Завершение работы с объектом Excel.Application

app.Quit();

System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

Пример как выбрать фаил и загрузив его и узнать количество заполненных строк и колонок в одном конкретном листе по имени.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

//поиск файла Excel

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect =false;

            ofd.DefaultExt = «*.xls;*.xlsx»;

            ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»;

            ofd.Title = «Выберите документ Excel»;

            if (ofd.ShowDialog() != DialogResult.OK)

            {

                MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

            string xlFileName = ofd.FileName; //имя нашего Excel файла

            //рабоата с Excel

            Excel.Range Rng;            

            Excel.Workbook xlWB;

            Excel.Worksheet xlSht;

            int iLastRow, iLastCol;

            Excel.Application xlApp = new Excel.Application(); //создаём приложение Excel

            xlWB = xlApp.Workbooks.Open(xlFileName); //открываем наш файл          

            xlSht = xlWB.Worksheets[«Лист1»]; //или так xlSht = xlWB.ActiveSheet //активный лист

            iLastRow = xlSht.Cells[xlSht.Rows.Count, «A»].End[Excel.XlDirection.xlUp].Row; //последняя заполненная строка в столбце А

            iLastCol = xlSht.Cells[1, xlSht.Columns.Count].End[Excel.XlDirection.xlToLeft].Column; //последний заполненный столбец в 1-й строке

Получаем список всех загруженных книг «листов» из файла

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

  //поиск файла Excel

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = false;

            ofd.DefaultExt = «*.xls;*.xlsx»;

            ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»;

            ofd.Title = «Выберите документ Excel»;

            if (ofd.ShowDialog() != DialogResult.OK)

            {

                MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

            string xlFileName = ofd.FileName; //имя нашего Excel файла

Excel.Workbook xlWB = ex.Workbooks.Open(xlFileName);

///загружаем список всех книг

            foreach (object item in xlWB.Sheets)

            {

                Excel.Worksheet sheet = (Excel.Worksheet)item;

            }

Blog / Import Excel to Datagridview using C#

In this tutorial, I will show you how to import an excel file to a DataGridview using C#. We are going to be using Microsoft.Office.interop.Excel namespace in this project. There are many ways to read an excel file in C#, but this is the easy way I found for beginners like me. Just follow the steps below.

Before we start, make sure that you have Visual Studio installed on your machine. If not, you can visit this download link. You can download the community version for free.

Let’s Start:

  1. First, Create a new Windows forma project. Navigate to File. Choose New option. Select Project.

Import Excel to Datagridview using C#

New project

2. From the New Project window. Name your project in any way you want. In my case, I name my project Upload_Data_From_Excel. Proceed on clicking the “Ok” button. See the image below.

Import Excel to Datagridview using C#

Name Project (Upload_Data_From_Excel)

3. Add controls from the toolbox. What we need is a Form, buttons, and OpenFileDialog.

  • Form
  • Button -> for the upload click event.
  • OpenFileDialog -> for browsing files.
  • DataGridview ->for viewing of data

Below image is the UI I created. This will help you visualize and understand the next step.

Import Excel to Datagridview using C#
Create design
  1. For clarity and easy navigating, we will rename our button. Click the button you added to your form and go to its property from the solution explorer and change the value. In my case, I name it as btn_Upload.
Import Excel
Change button name

5. Now navigate to your solution explorer and right-click on Reference, choose Add Reference, and then add Microsoft.Office.Interop.Excel.

Import Excel
Add Reference

6. From the reference manager window, expand Assemblies, and click Extensions from the left pane and search for Microsoft.Office.Interop.Excel from the middle pane.

Import Excel

Add Microsoft Office Interop

7. Verify if the reference is added. Go to your project solution explorer. Expand Reference, then look for Microsoft.Office.Interop.Excel.

Import Excel
Check Reference if Added

8. After we verify and successfully added Microsoft.Office.Interop.Excel. Open your form design and double click on the btn_Upload button to add button click event.

Import Excel

Double Click on button upload

9. Copy and paste the code below to your btn_Upload Click Event.

string file = ""; //variable for the Excel File Location
DataTable dt = new DataTable(); //container for our excel data
DataRow row;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Check if Result == "OK".
{
  file = openFileDialog1.FileName; //get the filename with the location of the file
  try {
    //Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file

    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

    Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);

    Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];

    Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;

    int rowCount = excelRange.Rows.Count; //get row count of excel data

    int colCount = excelRange.Columns.Count; // get column count of excel data

    //Get the first Column of excel file which is the Column Name

    for (int i = 1; i <= rowCount; i++) {
      for (int j = 1; j <= colCount; j++) {
        dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
      }
      break;
    }

    //Get Row Data of Excel

    int rowCounter; //This variable is used for row index number
    for (int i = 2; i <= rowCount; i++) //Loop for available row of excel data
    {
      row = dt.NewRow(); //assign new row to DataTable
      rowCounter = 0;
      for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
      {
        //check if cell is empty
        if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null) {
          row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
        }
        else {
          row[i] = "";
        }
        rowCounter++;
      }
      dt.Rows.Add(row); //add row to DataTable
    }

    dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview

    //close and clean excel process
    GC.Collect();
    GC.WaitForPendingFinalizers();
    Marshal.ReleaseComObject(excelRange);
    Marshal.ReleaseComObject(excelWorksheet);
    //quit apps
    excelWorkbook.Close();
    Marshal.ReleaseComObject(excelWorkbook);
    excelApp.Quit();
    Marshal.ReleaseComObject(excelApp);
  }
  catch(Exception ex) {
    MessageBox.Show(ex.Message);
  }
  1. Now you are ready to run your project and test if no error occurs. Run your application by pressing ctrl + f5 without debugging or f5 for debugging mode.
  • Click Upload button to upload.

Import Excel

Run Project
  • Then select your excel file. See the image below.

Import Excel

Open File

This is how to Import Excel to Datagridview using C# code. Hopes this helps.

Final output:

Excel File:

Import Excel

Excel File

Project Output:

Import Excel

Final Output

Full Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Upload_Data_From_Excel
{
    public partial class Upload_Data_Frm_EXCEL : Form
    {
        public Upload_Data_Frm_EXCEL()
        {
            InitializeComponent();
        }

        private void btn_upload_Click(object sender, EventArgs e)
        {
         string file = "";   //variable for the Excel File Location
            DataTable dt = new DataTable();   //container for our excel data
            DataRow row;
            DialogResult result = openFileDialog1.ShowDialog();  // Show the dialog.
            if (result == DialogResult.OK)   // Check if Result == "OK".
            {
                file = openFileDialog1.FileName; //get the filename with the location of the file
                try

                {
                 //Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file

                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                    Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);

                    Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];

                    Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;


                    int rowCount = excelRange.Rows.Count;  //get row count of excel data

                    int colCount = excelRange.Columns.Count; // get column count of excel data

                        //Get the first Column of excel file which is the Column Name                  

                    for (int i = 1; i <= rowCount; i++)
                    {
                        for (int j = 1; j <= colCount; j++)
                        {
                            dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
                        }
                            break;
                    }                       
                        //Get Row Data of Excel              
                    int rowCounter;  //This variable is used for row index number
                    for (int i = 2; i <= rowCount; i++) //Loop for available row of excel data
                    {
                        row = dt.NewRow();  //assign new row to DataTable
                        rowCounter = 0;
                        for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
                        {
                             //check if cell is empty
                            if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)
                            {
                                row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
                            }
                            else
                            {
                                row[i] = "";
                            }
                           
                            rowCounter++;
                        }
                        dt.Rows.Add(row); //add row to DataTable
                    }

            dataGridView1.DataSource = dt; //assign DataTable as Datasource for DataGridview

                   //Close and Clean excel process
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    Marshal.ReleaseComObject(excelRange);
                    Marshal.ReleaseComObject(excelWorksheet);
                    excelWorkbook.Close();
                    Marshal.ReleaseComObject(excelWorkbook);

                    //quit 
                    excelApp.Quit();
                    Marshal.ReleaseComObject(excelApp);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

        }

    }

}

Thank you for reading! Happy Coding!!

If you are interested in ASP.NET Core you may visit my Blog page for my latest post.

Also Read: Ethernut telecommunications

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.

Like this post? Please share to your friends:
  • Office guru excel vba
  • Office excel сохранить как
  • Office excel скачать последнюю версию
  • Office excel поздняя версия
  • Office excel оформить функцию