C# Excel Tutorial - #1 - Open and Read Excel Files

Поділитися
Вставка
  • Опубліковано 4 січ 2025

КОМЕНТАРІ • 496

  • @schwarzyzz7914
    @schwarzyzz7914 4 роки тому +3

    The easiest way availlable on the internet ! A big thank from a french student !

  • @СергейКостычев-х1о

    Hi! Thank you! How to close excel correctly? Even if I close VS after this code, my excel file doesn't open for editing.

  • @charavayfelix4475
    @charavayfelix4475 4 роки тому +5

    Hi,
    It doesn't work at the line 22. It say "Cannot implicity convert type 'object' to 'Microsoft.Office.Interlop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?) :(
    Do you have any idea ?

    • @TheBospear
      @TheBospear  4 роки тому +3

      I wonder why it sees it as object, older library maybe. In any case just cast it: ws = (Worksheet)wb.Worksheets[Sheet]; or: ws = wb.Worksheets[Sheet] as Worksheet;

    • @luisurenaalex2183
      @luisurenaalex2183 4 роки тому +3

      @@TheBospear " ws = (Worksheet)wb.Worksheets[Sheet];" fixed the problem

    • @keyounky
      @keyounky 4 роки тому

      @@luisurenaalex2183 thx dude it's worked

    • @Adomas_B
      @Adomas_B 4 роки тому

      @@TheBospear Thanks!

  • @armindashti8014
    @armindashti8014 6 років тому +8

    Thanks for the tutorial. but I got this error:
    System.Runtime.InteropServices.COMException: 'Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).'
    Why?

    • @kaifikhan
      @kaifikhan 5 років тому

      I am also getting the same exception and i am also stuck on it.

  • @paputec
    @paputec 6 років тому +4

    We have all had problems with path=" ". But the tutorial served me. Thank you

    • @TheBospear
      @TheBospear  6 років тому +1

      Blank path leads to Documents, you can just enter @"C:\Your Path\Test.xlsx" and target where ever you want.

    • @钱钧陶-l8z
      @钱钧陶-l8z 4 роки тому

      ​@@TheBospear I have tried @"C:\path\to\my\excel.xlsx" but it just doesn't work. VS says it can't find the specific file. .NET Core 3.1 WPF

    • @钱钧陶-l8z
      @钱钧陶-l8z 4 роки тому

      @@TheBospear I'm using Office 16. It seems like the package only applies to Office 15.

    • @TheBospear
      @TheBospear  4 роки тому

      @@钱钧陶-l8z Add open file dialog then
      www.c-sharpcorner.com/UploadFile/mahesh/openfiledialog-in-C-Sharp/
      and take it's path as the target file to avoid any confusion.

  • @dhannant
    @dhannant 5 років тому +5

    This is one of the best tutorials I've found and has gotten me the closest to a working excel function! Thank you very much. I'm hoping someone can answer my question though because it doesn't make sense to me. If I name the class "ExcelClass" rather than just "Excel" like in the tutorial OR if I change the "public Excel(string path, int sheet)" method to "public ExcelOpen(string path, int sheet)" I get an error that says Method must have a return type.
    Why would changing the name of the class or method throw this error?

    • @TheBospear
      @TheBospear  5 років тому +1

      Because when you have a class named Excel and a method named Excel that method is a constructor of the class and doesn't require a return type. If you want to rename ether of those just add void before your method name.

    • @bhootpurvmanusya
      @bhootpurvmanusya 2 роки тому

      honestly not even trying to sooth. but just to the point no jargon.

  • @bountypw7242
    @bountypw7242 3 роки тому +1

    EPIC tutorial MAN!!

  • @BCTAHbKA
    @BCTAHbKA 2 роки тому

    এটি সর্বকালের সেরা ভিডিও

  • @darius8171
    @darius8171 7 років тому +2

    Thank you very much! You helped me a lot! Do you have ideas how to read all data from .xlsx file , not just one column and row?

    • @dennisling5692
      @dennisling5692 7 років тому

      try doing for loop?

    • @darius8171
      @darius8171 7 років тому

      Yep, already

    • @TheBospear
      @TheBospear  7 років тому +4

      You got to loop for it, row by row, cell by cell. Treat it like a matrix. Only problem you can have with it is date and time writing and reading. I'll do a video soon on it and post the whole class to github.

    • @thomaskloiber7452
      @thomaskloiber7452 7 років тому

      wo muss die Testdatei abgespeichert werden?

    • @TheBospear
      @TheBospear  7 років тому +1

      You might want to go with english since google translate isn't all that good. Default path is Documents or My Document on older windows versions. Otherwize you can make a custom path to any location.

  • @yerkoantonioalvarez
    @yerkoantonioalvarez 4 роки тому +2

    Thanks for the video!. I'm starting at c# programming and there is something that i don't understand. why "wb" and "ws" don't have a "new" instance? aren't they an object?

    • @TheBospear
      @TheBospear  4 роки тому +4

      Objects don't have to be declared as new, they can be assigned straight from the initialization.
      Let's say you have a string that you want to have the value of "text". You can do String temp = new String(); temp = "text"; or you can do it straight away: string temp = "text"; You have created the object of type string temp with the "string temp" and now you only have to assign a value to it.

    • @yerkoantonioalvarez
      @yerkoantonioalvarez 4 роки тому

      @@TheBospearI clearly understand now, thank you so much!

  • @WanSyazlina
    @WanSyazlina 4 роки тому +2

    where is your excel file located in the project? I can't see it anywhere in the video.

    • @TheBospear
      @TheBospear  4 роки тому +1

      Documents

    • @messager3000
      @messager3000 4 місяці тому

      Yes, I had the problem, I moved the file into the Documents folder and it worked.

  • @natedurand
    @natedurand 4 роки тому +2

    What is on lines 1-12 of Form1.cs?

  • @uniquedesign5680
    @uniquedesign5680 3 роки тому +4

    Nice tutorial, But you didn't close the workbook, it can cause a problem even after closing the application. The solution is: make the wb variable public and use the wb.close() method after printing the message.

    • @andreeanita9135
      @andreeanita9135 2 роки тому +2

      I have the same problem. After i close the app a window appears which opens the excel file. I tried the wb variable public and close like you said, but i got this error as exception : System.Runtime.InteroopServices.COMException: '0x800401A8'.
      I tried also other functions for release the object like System.Runtime.InteroopServices.Marshal.ReleaseObject(wb)
      but i got stuck.
      I found a function which closes all excel files
      ( //using System.Diagnostics;
      Process[ ] excelProcs = Process.GetProcessByName("EXCEL");
      foreach(Process proc in excelProcs) {
      proc.Kill();
      } )
      but it is not recommended

    • @uniquedesign5680
      @uniquedesign5680 2 роки тому

      @@andreeanita9135 Share your code i might be able to figure out the issue.

  • @tatolelashvili3185
    @tatolelashvili3185 4 роки тому +1

    What a Great Tutor

  • @pebe26
    @pebe26 7 років тому +4

    Do I need to have Excel installed on my system to perform this?

    • @TheBospear
      @TheBospear  7 років тому +1

      Yes.

    • @Igor767
      @Igor767 6 років тому

      :(

    • @edgardopichardo
      @edgardopichardo 6 років тому +1

      I think you can download Microsoft.Office.Interop.Excel NuGet package to get the reference you need.

    • @UpamanyuYavalkar
      @UpamanyuYavalkar 6 років тому

      files-cdn.cnblogs.com/files/fan0136/Microsoft.Office.Interop.Excel.rar
      you can use this link to download the .dll, add this to the solution as reference and the Interlop namespace will be available

  • @FAAS12023000
    @FAAS12023000 2 роки тому

    Excelent! how to create and e
    run a macro vba excel from C# ?

  • @XxxDjNikxxX
    @XxxDjNikxxX 4 роки тому

    Thank you very much for this guide, it's very helpful!

  • @Grizzly12th
    @Grizzly12th 6 років тому +3

    I follow your step but when i run it's says
    System.InvalidCastException: 'Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).'

    • @TheBospear
      @TheBospear  6 років тому +1

      Remove using Microsoft.Office.Interop.Excel from the main class. Problem is you are calling custom class Excel and it's confusing it with dll Excel class.

    • @ertugrulozdemir2329
      @ertugrulozdemir2329 4 роки тому

      @@TheBospear I got this same problem but ı cant solved

  • @LE0p01d
    @LE0p01d 2 роки тому +1

    Thanks for the video! Could anybody explain to me please how can I close process named "excel" correctly in my task manager? After closing of my application I've got process named "microsoft excel". If I run my app several times I get several unclosed processes "microsoft excel". Actually I use my excel table once to copy data to array into C# and I don't need use excel anymore up to next launch of my application.

  • @connorkneeland3091
    @connorkneeland3091 4 роки тому +1

    Hey Bospear, I just followed this tutorial, and everything runs great except that the MessageBox.WriteLine(excel.ReadCell(0,0)); line doesn't pull up any message. I have a Test.xlsx file with a string in the correct box and have tried to output this message to the console instead, but still haven't gotten anything to pop up. Any ideas on what might be going wrong here?

    • @TheBospear
      @TheBospear  4 роки тому +1

      Put a break point inside ReadCell method, see if you get anything. Also you placed Test.xlsx in the Documents folder?

    • @connorkneeland3091
      @connorkneeland3091 4 роки тому +1

      @@TheBospear I placed Text.xlsx in the documents folder and put a breakpoint inside the ReadCell method, but it gave me the same result as before. When I put a breakpoint in the Program.cs file, it goes into the Application.Run(new Form1()) line, then inside the Form1.cs file it runs through the Form1() function and ends. Should I be making a call to Form1_Load inside the public Form1() function? And if so, what would be the parameter for the EventArgs e? Thank you for your help!

    • @TheBospear
      @TheBospear  4 роки тому +1

      @@connorkneeland3091 Just double click on the form and it will give your Form_Load event. Mind if you paste your code here so I can take a look?

    • @connorkneeland3091
      @connorkneeland3091 4 роки тому +1

      @@TheBospear I tried double-clicking and unfortunately got no result. Here is the code I have
      Form1.cs:
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      namespace ImportExcel2
      {
      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();
      }
      private void Form1_Load(object sender, EventArgs e) //File name, worksheet number
      {
      OpenFile();
      }
      public void OpenFile()
      {
      Excel excel = new Excel(@"C:\Users\Conno\Documents\Test.xlsx", 1);
      //Console.WriteLine(excel.ReadCell(0, 0));
      //MessageBox.Show(excel.ReadCell(0, 0).ToString());
      MessageBox.Show(excel.ReadCell(0, 0));
      }
      }
      }
      Excel.cs
      using System;
      using System.Collections.Generic;
      using System.Text;
      using Microsoft.Office.Interop.Excel;
      using _Excel = Microsoft.Office.Interop.Excel;
      namespace ImportExcel2
      {
      public 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 = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[Sheet];
      }
      public string ReadCell(int i, int j) //Row, Column
      {
      i++;
      j++;
      if (ws.Cells[i, j] != null)
      return ws.Cells[i, j].ToString();
      else
      return "";
      }
      }
      }
      Program .cs
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using ImportExcel2;
      namespace ImportExcel2
      {
      static class Program
      {
      ///
      /// The main entry point for the application.
      ///
      [STAThread]
      static void Main()
      {
      Application.SetHighDpiMode(HighDpiMode.SystemAware);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
      }
      }
      }
      In the Excel.cs file, I do not make a call to the Value2 function since I don't have that or think that I need it.

    • @TheBospear
      @TheBospear  4 роки тому +1

      @@connorkneeland3091 Use .Text instead of .Value2

  • @anthonykurniajaya4938
    @anthonykurniajaya4938 4 роки тому +1

    Hi there! It's really interactive tutorial. I have a question, I have an error said that "Program does not contain a static 'Main' method suitable for an entry point". Also, I am a little bit confused where I need to put my excel document, maybe you could answer it?

    • @TheBospear
      @TheBospear  4 роки тому +1

      Excel file goes in Documents folder if you're not changing the path. As for the error ether create a Forms project that auto generates main in Program.cs or put the code for Load method inside Console projects main method. Can't mix and match console and form projects.

  • @נתנאלאדר-מ5ל
    @נתנאלאדר-מ5ל Рік тому

    Thanks a lot!! Very helpful!

  • @blazept567
    @blazept567 7 років тому +3

    Perfect. Thank you, sir!

  • @rronfrangu1103
    @rronfrangu1103 3 роки тому

    These Tutorials are really helpful. Thank you. Does anyone have any idea how can i read the background color of a cell in Excel? I need this, so i can make the same color for the background of the textbox.

  • @coyotemoon722
    @coyotemoon722 5 років тому +1

    @Bospear. How do you implement the Application Interface? I'm getting errors when using the _Application syntax.

    • @TheBospear
      @TheBospear  5 років тому

      _Application is an object within Interop.Excel library, just make sure you have all using statements. If it still persists you can do _Excel.Application excel = new _Excel.Application();

    • @coyotemoon722
      @coyotemoon722 5 років тому

      @@TheBospear Interesting, I had my Excel class named something other than "Excel" so that's why it caused errors. I named it "Excel_Stuff.cs" because it was just a learning exercise. Is there a reason this class has to be named so definitively?

    • @TheBospear
      @TheBospear  5 років тому

      @@coyotemoon722 It shouldn't, I guess it came to some naming polymorphism between interop library and the class. I'll check it out one of these days to see what's up.

    • @jbond5834
      @jbond5834 5 років тому

      I have the some error. It might have something to do with the VS version. Mine is VS2013

  • @kenma6432
    @kenma6432 7 років тому

    Thanks for the clear explanation SIr. I am new to C# programming and starting using visual studio, I have followed the procedure but I cannot get the expected result, do I have to type anything in the Main() of program.cs? Thanks!

    • @TheBospear
      @TheBospear  7 років тому +1

      No, when you use forms in C# you generally don't do anything with Main function, unless you need to pass outside arguments. What are you getting as a result?

    • @kenma6432
      @kenma6432 7 років тому

      I can get nothing from the program, I think it directly runs the empty Main().
      Firstly I created Console application which is the program.cs, then I added a class(Excel.cs) and Form with the "Load" event handler, but I can get nothing. Thank you so much sir!

    • @TheBospear
      @TheBospear  7 років тому +1

      Yea, that will happen if you make a console application and add form later. So just add the main form at the start. Write in Main() this:
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
      new Form1 is the name of the start Form you made.

    • @kenma6432
      @kenma6432 7 років тому +1

      Thanks! Will try later!

    • @kenma6432
      @kenma6432 7 років тому

      Sir, do you have any idea on this error happens in the code "wb = excel.Workbooks.Open(path);" : "Cannot convert COM object 'Microsoft.Office.Interop.Excel.ApplicationClass' to
      interface type 'Microsoft.Office.Interop.Excel._Application"
      (p.s. The message is not directly copied from visual studio as I am not using English language pack, I tried to translate the error message into English)
      Thank you so much!

  • @microsecure2612
    @microsecure2612 4 роки тому +1

    thanks for this tutorial
    I have a question pls:
    how to open file from network drive using c#?
    thx

    • @TheBospear
      @TheBospear  4 роки тому +1

      Add the location of the network drive and path to the file in the path variable. So it's exactly the same way you would do on local. If your network drive requires admin rights access run the app or VS as admin.

    • @microsecure2612
      @microsecure2612 4 роки тому

      thank you very much for this
      i have another question pls:
      i did create a simple form with a button, i need this button to open a folder and this folder exist in one of our servers
      do you have this code pls
      many thanks

    • @TheBospear
      @TheBospear  4 роки тому

      @@microsecure2612 If you want to choose a file from that folder to load the path do the open file dialog with network location as the default (microsoft has example in documentation, can't write it out on a phone). If you just want to open in explorer I think System.Diagnostics.Process.Start targeting the folder would do the trick.

    • @microsecure2612
      @microsecure2612 4 роки тому

      @@TheBospear
      Thank u very much for ur info:
      Is it possible to have ur email address then i can email u back my simple code to check it pls ?
      Thx

    • @TheBospear
      @TheBospear  4 роки тому

      @@microsecure2612 pastebin it here, however I'm not sure when I'll have the time to review it. Could take few days

  • @robvanbreemen6660
    @robvanbreemen6660 5 років тому

    Hi , thank you for sharin your knowledge. I've tried the above. Everything works but i cant receive a list of items. Do i need to parse the readcell to a list? I thought the int i++ and j++ would return each value when not null and show it in the messagebox. Hope you can help out.

    • @TheBospear
      @TheBospear  5 років тому

      value2 returs all values from a specific cell, regardless if it's null (returns as empty string), if you want to grab everything from a sheet one of the later tutorials shows how to do it, I think it's No5, you also have in the comment how to grab only used cells

  • @Spirittism
    @Spirittism 3 роки тому

    Could you expand on this video? like how to count the rows or columns or how to input into database?

    • @TheBospear
      @TheBospear  3 роки тому +2

      This is kind of a specific tutorial, made to show people how to use interop at the time when microsoft didn't have proper documentation for it. If you want to count rows/columns as per new microsoft documentation TargetWorksheet1.UsedRange.Rows.Count - 1; same for columns.
      As for the database part that's a gigantic question, and I suggest you look up C# integration for the specific database you need.

  • @danielvargas1537
    @danielvargas1537 5 років тому +1

    in the part where it is done the pucblic Excel etc etc i have a problem. Visual studio said that i need a return, but u dont have a return in this part. What i can do?

    • @danielvargas1537
      @danielvargas1537 5 років тому +1

      Nvm, i saw the problem xD

    • @kylekastilahn
      @kylekastilahn 5 років тому

      he has return type in the method that was created as string with two returns in the body probably doesn't need the else part but that a different story.... for the constructor which is the public Excel , it is called in the main method with an initialization using new So in the static void Main{string [ ] , args) { Excel excel = new Excel("pathOfFile", 1);} //that is in the program.cs file, I would first make sure you're not trying to call the Excel object like a method in the program file, then check that you wrote the constructor correctly.

  • @pop2mcar
    @pop2mcar 5 років тому +1

    Hi, experienced but rusty programmer here... The program runs but no message. When I debug/trace the steps in Form1.cs, it never gets past InitializeComponent(); it goes to program.cs (Main) and ends after Application.Run(new Form1())

    • @pop2mcar
      @pop2mcar 5 років тому +1

      Like I said, Rusty...I was missing code in the initializecomponent from the form1.designer.cs. I just used the events window to make sure it loaded (lazy lol).

    • @TheBospear
      @TheBospear  5 років тому

      @@pop2mcar Piece of advice when working with forms, don't stacktrace from Program.cs, it's there only to start the form class as a single thread apartment. Constructor is usually there only to set constants and initialize controls/events. In this case start from Form_Load event, it triggers when all controls in the form are loaded.
      Actually always start to trace from an event rather than a constructor when working with a form, be it Load, or Click etc.

  • @invazorzimutube
    @invazorzimutube 5 років тому +3

    I am having troubles with Value2 and the Excel type in the form1. Can anyone give me some sugestions please

    • @zanekross9649
      @zanekross9649 4 роки тому

      Did you ever find a solution for this? I'm having the exact same problem

    • @Adomas_B
      @Adomas_B 4 роки тому

      I just didn't type .Value2 and it worked for me

    • @invazorzimutube
      @invazorzimutube 4 роки тому

      ​@@zanekross9649 Sorry for the late response. This was a very old project I was in and I don't really remember. I hope you find ​ @Adomas B 's respnse convenient

  • @radhikakurakula1425
    @radhikakurakula1425 2 роки тому

    Hi i have one doubt how can we load same data to down list based on select query and condition

  • @jackwinter2669
    @jackwinter2669 6 років тому +8

    How do you close the excel file when you're done? My file is now locked and I can't edit it with excel anymore.

    • @TheBospear
      @TheBospear  6 років тому +5

      Yea, my bad. In later videos I made the close statement but that one is bad as well.
      Just put a new method in the Excel class
      public void Close()
      {
      wb.Close(0);
      }
      and than call it after the read from the form.
      As for file you opened right now just kill excel.exe processes from task manager and that will clear it up.

    • @jackwinter2669
      @jackwinter2669 6 років тому +3

      Thank you so much! I just spent the last 2 hours trying to figure it out on my own.

    • @Matrix21rms
      @Matrix21rms 6 років тому +3

      2 hours is a lot :)

    • @slazper
      @slazper 4 роки тому

      @@TheBospear I placed above code in the Excel class without any errors. But I added below in the Form1.cs and "Close()" does not appear to recognized as the Excel class and Close method but instead just closes the form.
      private void button2_Click(object sender, EventArgs e)
      {
      Close();
      }

    • @TheBospear
      @TheBospear  4 роки тому

      @@slazper Object oriented programming, you need to call a method in the object (instance of class) you want. Close in Form is upon Form object, Excel excel = new Excel(...); excel.Close(); works upon Excel object.
      I suggest you look in to C# and Object oriented programming tutorials if you want to make a c# app with this first. It's a really big gap in knowledge you need to fill if comments here are to be effective.

  • @tarktastan7100
    @tarktastan7100 5 років тому

    Thank you so much ! I used this codes in my app. But I need to count my rows . How can I do that ?

    • @TheBospear
      @TheBospear  5 років тому +2

      Easiest way would be
      int i = 0;
      while(true)
      {
      if(string.IsNullOrEmpty(excel.readcell(i, 0))
      break;
      i++;
      }

    • @tarktastan7100
      @tarktastan7100 5 років тому +1

      @@TheBospear Thank you so much ! :)

  • @Felifoxy
    @Felifoxy 3 роки тому

    It works except for one thing. I am not able to edit or delete the excel file now. How can this be fixed?

  • @kumarayush3556
    @kumarayush3556 3 роки тому +1

    can anyone help me out with the method to read excel file and view it into datagrid.

  • @10tronic
    @10tronic 4 роки тому +1

    Hi. I can´t undestand the line:
    _Application excel = new _Excel.Application();
    why I am able to instantiate the “Application” interface?

    • @TheBospear
      @TheBospear  4 роки тому +1

      Good question. You're not instantiating an interface, you're instantiating an abstract class inheriting it (or at least I think it's an abstract class, been a while since I looked it up) and VS is just reporting it as interface

    • @TheBospear
      @TheBospear  4 роки тому +1

      Sory, concrete class, not abstract class.

  • @farshidmousavi109
    @farshidmousavi109 7 років тому +2

    Sir I do have a problem, I put the line of path as this
    Excel1 excel = new Excel1 (@"‪C:\Users\farshidmoosavi\Desktop\Revit API\first.xlsx", 1);
    and it says we cannot find the address, althogh the address is correct

    • @farshidmousavi109
      @farshidmousavi109 7 років тому +1

      the problem has been solved

    • @TheBospear
      @TheBospear  7 років тому +2

      Do post a solution please, just in case someone else manages to stumble at the same problem.

    • @farshidmousavi109
      @farshidmousavi109 7 років тому +1

      I was just entering a wrong Path, once I get it corrected, it's been solved.

    • @TheBospear
      @TheBospear  7 років тому +3

      If I had a dollar every time that happened to me... I wouldn't need a job any more :D

  • @anon0912
    @anon0912 4 місяці тому

    How do you close the file? I had to save my spreadsheet as a different one because it got locked in read-only mode.

  • @billmaragos2812
    @billmaragos2812 6 років тому +2

    I have a problem with the path. Either if I write 'string path = "";' or the same with the path of the TEST.xlsx file, it still doesnt compile, giving me the error: 'System.Runtime.InteropServices.COMException: ''TEST.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.'
    and marking ' wb = excel.Workbooks.Open(path); '.
    Can you/anyone help please ?

    • @TheBospear
      @TheBospear  6 років тому +2

      @"Test.xlsx" is in my documents for the excel interop, not in the root folder. I guess that's the problem. Try with a global path like @"C:\ExcelTestFolder\Test.xlsx"

    • @billmaragos2812
      @billmaragos2812 6 років тому

      Thanks for the reply. I now created a folder straight in C:\ called 'excel test folder' and put the 'TEST.xlsx' document in it. In the program i wrote this: 'string path = @"C:\excel test folder\TEST.xlsx";' and it doesnt work. I also tried typing two backslashes (\\) instead of one but I always end up with the same error... Im almost losing it... In any case, thanks for the video and the reply in the first place.

    • @TheBospear
      @TheBospear  6 років тому

      Always. Are you sure it's xlsx and not xls or xlsm?

    • @jorgateme
      @jorgateme 6 років тому +2

      @@billmaragos2812 It worked for me by avoiding space in folder name. I hope, it would work for you too.

    • @billmaragos2812
      @billmaragos2812 6 років тому

      @@jorgateme thanks for the reply !

  • @jeremyflowers8908
    @jeremyflowers8908 5 років тому

    Do you not have to preface wb, ws and excel with 'this' in C# within the Excel constructor?

    • @TheBospear
      @TheBospear  5 років тому

      not needed, there's nothing conflicted.

  • @natedurand
    @natedurand 4 роки тому

    When I try to run Form1.cs, I receive the following popup window:
    "A project with an Output Type of Class Library cannot be started directly. In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project."
    It seems like I created Form1 as the wrong type of file. I know this is too basic of a question to be asking here, but do you have any recommendations of how to create it properly? I created it through File -> New -> Visual C# class

    • @TheBospear
      @TheBospear  4 роки тому

      File -> New -> Project -> Windows Forms Project (or Windows Forms App depending on the version). That also answers your question about lines 1-12, auto generated code.

  • @Cmerk10
    @Cmerk10 2 роки тому

    Hi, i have two question
    1) This function works only project on NET. Framework; is it correct? Because with a project in NET. Core right at the start i have an expection that say it can't open/recognize the file (other 'problem' is that the compiler want to force me the cast on worksheet)
    2) Could i specify the worksheet that i want to read?
    I created more worksheet on excel file, but it opens only the first (obviously i try to change the value 'Sheet' when i create the object Excel)

    • @TheBospear
      @TheBospear  2 роки тому +1

      Framework only and yes you can open other sheets, both by their name and their number.

    • @Cmerk10
      @Cmerk10 2 роки тому

      Thanks for the confirmation and video 😁💪💪

    • @TheBospear
      @TheBospear  2 роки тому

      @@Cmerk10 Excel ex = new Excel("excel.xlsx", 2); number is the sheet number

    • @Cmerk10
      @Cmerk10 2 роки тому

      @@TheBospear Yes, excatly, my mistake!. Because i am working with two excel files. The second worksheet was added in only one of them. In my program i was calling the other file. Anyway thank you again !

  • @sarahabraham7248
    @sarahabraham7248 4 роки тому +1

    It shows an error "Program does not contain a static "Main" method suitable for an entry point"

    • @TheBospear
      @TheBospear  4 роки тому

      Make a Forms project to follow this step by step, not Class Library or Console application. Alternatively I suggest looking in to basic C# tutorials

  • @sageoffaith
    @sageoffaith 2 роки тому

    I do not have the microsoft.office library. How can I obtain this? I am using visual studios 2022 and can't find it online. Or at least in english.

    • @TheBospear
      @TheBospear  2 роки тому

      Install excel, lib comes with it. Or you can get it from nuget www.nuget.org/packages/Microsoft.Office.Interop.Excel

  • @WingBeatZ
    @WingBeatZ 5 років тому +1

    Great tutorial.. But I am having a problem.. I can't get the MessageBox to show up.. I have gone over the code 1000 times now, it is exacly the same as shown in the video.. I get no errors when compiling and the form1 window pops up, but not the message box. I have tryd moving the TEST.xlsx to diffrent locations and add it to the path line.. Any clue? Would like to continue with the tutorials, but not until I know it works for me xD
    Ps. Also tryd running VS as admin.

    • @TheBospear
      @TheBospear  5 років тому +1

      What you can do is instead of MessageBox.Show(excel.readCell(0,0)) do string temp = excel.readCell(0,0); MessageBox.Show(temp); Breakpoint on messagebox line and see if temp has a value (hover over it with a mouse) of the excel cell. Depending on that we can see what's going on. (Just a heads up, path for file is C:\Users\"Current User"\Documents\TEST.xlsx")

  • @SamRechym1
    @SamRechym1 6 років тому

    Hey Bospear,
    I haven't been able to produce the "TEST" line, I have an excel document saved to my desktop. I have no build errors or anything, but the fact that this was built in WinForms keeps producing a blank Form field. I have "MessageBox.Show(excel.ReadCell(0,0)); " and all the code line for line, but the Form1.designer page was never shown, so I have no reference here to see what you've done on the design. Please help.
    Thanks,
    Jamie

    • @TheBospear
      @TheBospear  6 років тому

      Done nothing to the design, you can run the same code on console or dll (which is kind of a plan at the end of the series), but the path shown in the video is targeting Documents, so check if you have a correct path for the file you have.

    • @SamRechym1
      @SamRechym1 6 років тому

      Hey man thanks for the maintenance you do on here. I realized a piece of code was misplaced, had to move it and it was good to go. Your explanation for document root path is great, thank you.

    • @TheBospear
      @TheBospear  6 років тому

      You're very welcome.

  • @muntaqimtechnicalbaloch5107
    @muntaqimtechnicalbaloch5107 2 роки тому

    Hey Bospear, I followed your every step it was osm code but i have issue in form1 backend code
    that is it is not accepting Excel as class for excel object error message "Excel is alias but it is used as type"
    plz guide me

    • @TheBospear
      @TheBospear  2 роки тому

      post the line of code that's giving you the error

  • @rajeshkale7849
    @rajeshkale7849 2 роки тому

    Hi i am getting error like class not registered when my cursor coming to the application() constructor it is throwing exception please reply

    • @TheBospear
      @TheBospear  2 роки тому

      I don't remember making an application() method

    • @rajeshkale7849
      @rajeshkale7849 2 роки тому

      No I am asking you I have written code like
      Application obj= new application();
      And I have use namespace is
      Microsoft.Office.interop.excel.
      When my cursor coming to application () method it is throwing exception please reply

    • @TheBospear
      @TheBospear  2 роки тому

      @@rajeshkale7849 Ok, first of, namespace should be name of the project, or name of a part of the project, you cannot use a library name as a namespace. Second, I can't know what problem you have in a code I haven't written or seen. Ether follow the tutorial or post your custom code.

  • @mau-nguyen-van
    @mau-nguyen-van 6 років тому +1

    Why in .NET 3.5 or less than my app don't read Excel file
    this's my mistake:" Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?)".
    Thank you. Guy

    • @RodrigoSouza-dc4xd
      @RodrigoSouza-dc4xd 5 років тому

      stackoverflow.com/questions/19888326/cannot-implicitly-convert-type-object-to-microsoft-office-interop-excel-works

    • @Adomas_B
      @Adomas_B 4 роки тому

      type ws = (Worksheet)wb.Worksheets[sheet];

  • @meliseyka
    @meliseyka 11 місяців тому

    thx. but it doesn't work for me. Is there a way how to open and read excel file in WPF?

    • @TheBospear
      @TheBospear  11 місяців тому +1

      Access to interop objects in WPF is the same as Forms, I guess that office version, and interop lib with it, is different. I suggest you read following two:
      learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/how-to-access-office-interop-objects
      stackoverflow.com/questions/68981380/load-the-excel-file-which-i-open-using-dialog-box-in-wpf-into-datagrid-when-i-cl

  • @TerraCalc123
    @TerraCalc123 3 роки тому +1

    Thanks, in my case Value2 returns an object not an string,
    Object valor = ((_Range) ws.Cells[i, j]).Value2;
    ---
    using _Range = Microsoft.Office.Interop.Excel.Range;
    ....
    In the instance parte ToString() or whatever.
    thanks for the video.

    • @abhijeetjoshi6103
      @abhijeetjoshi6103 3 роки тому

      Dis u got a solution? I am also facing same issue at value2...

  • @simxschl
    @simxschl 4 роки тому +1

    Mhh, for me this didn't work with the "private void Form1_Load(object sender, EventArgs e) { OpenFile(); }"
    But when I called OpenFile() from "public Form1() { }" just above it, it was finally executed correctly.
    And I have no idea where you had to put the excel file to be able to call it by (@"TEXT.xlsx", 1), I had to put in the complete path...

    • @TheBospear
      @TheBospear  4 роки тому +1

      Think you're missing initialize in the Form constructor, which is strange since it's a default call when you make a form. As for location it's in Documents.

    • @JasonACharles
      @JasonACharles 4 роки тому

      So did you find out what was missing? Have the same problem and your work-around just helped, but what is missing?

    • @TheBospear
      @TheBospear  4 роки тому

      @@JasonACharles Form_Load method was missing, double click the form and it will be added automatically.

    • @JasonACharles
      @JasonACharles 4 роки тому

      @@TheBospear thx, that did the trick

  • @Adhodge1992
    @Adhodge1992 4 роки тому

    I am using all the same namespaces and added the references. However, value2 is not working in line 29 of your video.

    • @TheBospear
      @TheBospear  4 роки тому

      15.0 library. try with ((Excel.Range)wb.cells[i,j]).Value2

    • @danielafrancos.9953
      @danielafrancos.9953 3 роки тому

      check this code here is the problem solved:
      ----
      using System;
      using Microsoft.Office.Interop.Excel;
      using _Excel = Microsoft.Office.Interop.Excel;
      namespace mysheet
      {
      class Excel
      {
      string path = "";
      _Application excel = new _Excel.Application();
      Workbook wb;
      Worksheet ws;

      static void Main(string[] args)
      {
      Excel excel = new Excel("C:\\Temp\\baldo.xlsx",1);
      Console.WriteLine(excel.readCell(0,0));
      // Excel(@"C:\Temp\baldo.xls", 1);
      //Excel("C:\\Temp\\baldo.xls", 1);
      }
      public Excel(String path, int Sheet)
      {
      this.path = path;
      wb = excel.Workbooks.Open(path);
      ws = wb.Worksheets[Sheet];
      Console.WriteLine("Hello World!");

      }
      public string readCell(int i, int j)
      {

      i++;
      j++;
      if (((_Excel.Range)ws.Cells[i, j]).Value2 != null)
      return ((_Excel.Range)ws.Cells[i, j]).Value2;
      else
      return "";


      }
      public void writeToCell(int i, int j, string s)
      {
      }
      }
      }

  • @MichaKurzewski
    @MichaKurzewski 6 років тому +1

    If i have a library no. 16 for Excel and some users would have older libraries on their computers(like 15), I guess this won't work?

    • @TheBospear
      @TheBospear  6 років тому +1

      Worked with 14 when I started making excel automaton. Don't know about older than 14 but newer will work. Also there should be NuGet packs for 14, 15 and 16 which should be a free download.

    • @edgardopichardo
      @edgardopichardo 6 років тому +1

      think you can download Microsoft.Office.Interop.Excel NuGet package to get the reference you need

  • @frankringwald4315
    @frankringwald4315 4 роки тому

    hey I did everything as you showed in the video but for some reason its not working. When I run the program an empty default Form Window is being displayed but nothing else. The initializeComponent() method is being executed which looks like this:
    private void InitializeComponent()
    {
    this.components = new System.ComponentModel.Container();
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(800, 450);
    this.Text = "Form1";
    }
    after that the program just finishes without executing the other methods like OenFile() etc.
    Can you please tell me what Im missing here?

    • @frankringwald4315
      @frankringwald4315 4 роки тому

      my main method in prgoram.cs looks like this:
      static void Main()
      {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
      }
      Form1 looks like this:
      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();
      }
      public void Form1_Load(object sender, EventArgs e)
      {
      OpenFile();
      }
      public void OpenFile()
      {
      Excel excel = new Excel(@"emails.xlsx", 1);
      MessageBox.Show(excel.ReadCell(0, 0));
      }
      }

    • @TheBospear
      @TheBospear  4 роки тому

      @@frankringwald4315 Breakpoint on OpenFile method, start stepping through and see where it breaks.

  • @edwinpeterdionisio5284
    @edwinpeterdionisio5284 6 років тому

    sir is it possible to open microsoft publisher also using visual studio 2017? coz i need to print the data in visual studio 2017 using publisher. please help me TIA

    • @TheBospear
      @TheBospear  6 років тому

      There is a publisher interop library, but I haven't used publisher before so no idea how to use the library.

    • @edwinpeterdionisio5284
      @edwinpeterdionisio5284 6 років тому

      yes i know but i dont know how to use it. is there any alternative way for me to print the data from database coz i need to print after searching it, TIA

    • @TheBospear
      @TheBospear  6 років тому

      Here's a couple of links that might help:
      Opening and exporting a file.
      csharp.hotexamples.com/examples/Microsoft.Office.Interop.Publisher/Application/Open/php-application-open-method-examples.html
      Reading and manipulating text.
      www.vbforums.com/showthread.php?554733-Find-and-replace-text-in-MS-Publisher-file
      Last one is in VB, but interop works the same so you can rewrite it in c# in few minutes.

  • @have-z5h
    @have-z5h 6 років тому

    Hi Bospear
    I am confusing that why you have both Excel.cs and Program.cs in the same time?

    • @TheBospear
      @TheBospear  6 років тому

      Separate classes based on their logical wholes. Program.cs is a default class that any c# project uses, Excel.cs is made to handle just Excel calls. But you shoot look in to tutorial about Object oriented programming a bit more in depth before continuing, it will do you more good.

    • @have-z5h
      @have-z5h 6 років тому

      @@TheBospear
      Thank you .Then I will .

  • @faab007nl
    @faab007nl 5 років тому

    I'm getting the error:
    System.InvalidCastException
    HResult=0x80004002
    Message=Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Workbook'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208DA-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
    Source=
    StackTrace:

  • @shhhomi
    @shhhomi 7 років тому

    hello i have a question,i imported excel file to windows forms application,and i need to import graph from that same file,but i don't have an idea how to do it,if you could give me any suggestions i would be realy grateful.

    • @TheBospear
      @TheBospear  7 років тому

      Never tried, honestly I only work with data. I guess you imported data that make that chart, so you can use that data to make a chart in the form. msdn.microsoft.com/en-us/library/dd489237.aspx

  • @qlBlitzlp
    @qlBlitzlp 4 роки тому

    How to specify the path to the file so that it is in the same folder as the exe file without entering the full path?

    • @TheBospear
      @TheBospear  4 роки тому

      AppDomain.CurrentDomain.BaseDirectory

    • @qlBlitzlp
      @qlBlitzlp 4 роки тому

      Thank you! Another question: can I find out the count of non-empty cells in a column? I need to take a random cell in a column: int Rand = R.Next(1, ???);

    • @TheBospear
      @TheBospear  4 роки тому

      @@qlBlitzlp just go through the column and test for string.IsNullOrEmpty

    • @qlBlitzlp
      @qlBlitzlp 4 роки тому

      Thanks! I thought there was a special function for this.

  • @nikosnikisianlis7573
    @nikosnikisianlis7573 4 роки тому

    hi thank you very much for the help the program is perfect but I have a problem
    if the cell contain a word for example "test" everything is perfect but if the cell contain number the I have this error :
    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot implicitly convert type 'double' to 'string''
    can you help me;

    • @TheBospear
      @TheBospear  4 роки тому

      Microsoft at one point decided that we have to be protected from our own conversion..... so just do return (String)ws.Cells[i,j].Value2 or return ws.Cells[i,j].Value2 as String.

  • @MegaDav11
    @MegaDav11 4 роки тому

    How could I find some text in the Excel file and copy the cell next to it into the text file?

    • @TheBospear
      @TheBospear  4 роки тому

      By following this tutorial to get the text from excel and then using StreamWriter to write it

    • @MegaDav11
      @MegaDav11 4 роки тому

      @@TheBospear thank you and a one problem, why I can't ws = wb.Worksheets[Sheet];

    • @TheBospear
      @TheBospear  4 роки тому

      @@MegaDav11 Need more info than that, like the error you get

    • @MegaDav11
      @MegaDav11 4 роки тому

      @@TheBospear Error CS0266 The object type cannot be converted to Microsoft.Office.Interop.Excel.Worksheet by default. There is an explicit transfer

    • @TheBospear
      @TheBospear  4 роки тому +2

      @@MegaDav11 Different interop library, just do ws = (Worksheet)wb.Worksheets[Sheet];
      or ws = wb.Worksheets[Sheet] as Worksheet;

  • @srinivasu2953
    @srinivasu2953 3 роки тому

    Can we able to read a Image ?

  • @Swakke31
    @Swakke31 3 роки тому

    Maybe next time show us which template you used and where you need to put the excel file.

    • @TheBospear
      @TheBospear  3 роки тому

      This tutorial was made because Microsoft had no documentation on the library back then. Template as any intern can see plainly is windows forms (not that it matters, you can use the same class in any .net framework project). As for location of the excel file I think that it's in the second tutorial, if not it's the default working directory, which is Documents.

    • @Swakke31
      @Swakke31 3 роки тому

      @@TheBospear I have tried a windowsformsapp template, but can not run it because of the static main thats missing in your program.

    • @TheBospear
      @TheBospear  3 роки тому

      @@Swakke31 static void main is the entry method in all C# applications, it is not missing. Make a new windows forms application .Net Framework and do exactly what I did in the tutorial.

  • @tuphanhoang9074
    @tuphanhoang9074 5 років тому

    help me, plesase : An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in WpfApplication1.exe

  • @arturoroche3782
    @arturoroche3782 3 роки тому

    04:00 ReadCell

  • @messager3000
    @messager3000 4 місяці тому

    First you need to create a Windows Forms Application, in which you can double-click on the main form in the form designer to have your Form1_Load() method to be automatically generated.
    And you need to store your Excel file into your Windows documents folder.
    You shall also implement a Close() method in your Excel class in order to avoid the presence of a residual Excel instance and "~$Test.xlsx" file like this :
    public void Close()
    {
    if (wb != null)
    {
    wb.Close();
    }
    }

  • @karimalramlawi7228
    @karimalramlawi7228 3 роки тому

    Does it work on Excel in Microsoft 365?
    Or do i need to download Excel 2013?

    • @TheBospear
      @TheBospear  3 роки тому

      It does. In fact I think the videos were recorded on 365, and the OG project I did before deciding to make these videos was on 365

  • @bupolsdupro124
    @bupolsdupro124 4 роки тому

    Where do you put the excel file so that the program can find it?

  • @roccoguarino9136
    @roccoguarino9136 3 роки тому

    Hi for me it works only if I put the OpenFile() inside the method Form1. Could you explain me why? What is the function of the method Form1_Load? Thk

    • @TheBospear
      @TheBospear  3 роки тому +1

      Form1_Load gets called when Form UI is generated. So if you started a console rather than a Form app Form1_Load will not be called. Also, Form1_Load is an event listener, you make the even by double clicking Form UI in the UI tab or by adding the event in form properties (or you can make event by your self but why would you do that manually)

    • @roccoguarino9136
      @roccoguarino9136 3 роки тому +1

      @@TheBospear thk for the help. When I create the project I used the Form app. I am new to Visual Studio so I did not catch your suggestion. Could you be more specific? Thk

    • @TheBospear
      @TheBospear  3 роки тому +1

      @@roccoguarino9136 It doesn't get any more specific than that unless I picture guide you. So this might be better ua-cam.com/video/XK0xXQtyt_U/v-deo.html

    • @roccoguarino9136
      @roccoguarino9136 3 роки тому

      @@TheBospear thk you so much

  • @قراءات-غ4ظ
    @قراءات-غ4ظ 6 років тому

    what Csharp version you're working with?

    • @TheBospear
      @TheBospear  6 років тому

      If I can remember correctly this was C# 7.0

    • @قراءات-غ4ظ
      @قراءات-غ4ظ 6 років тому

      @@TheBospear hiii bospear! can you give me your email? im working on a specific App that deals with excel values and i have no idea from where to start,,, i really apreciate your help
      thanks

  • @AlexPitsi
    @AlexPitsi 5 років тому

    i'm not able to access the Value2 property. why might that be? i've double and triple checked and i've done everything the way you showed

    • @TheBospear
      @TheBospear  5 років тому

      There could be a number of things, different library, com bug, wrong object lookup etc. post your code here and let me take a look to eliminate most of the possibilities

    • @AlexPitsi
      @AlexPitsi 5 років тому +1

      @@TheBospear I ended up being able to access it but I had to use the worksheet as a range

    • @TheBospear
      @TheBospear  5 років тому

      @@AlexPitsi Could be a newer or older library, or a com bug... it happens more often than it doesn't

    • @garrfildcsgomore4609
      @garrfildcsgomore4609 4 роки тому

      @@TheBospear How do u use it as a range?

    • @TheBospear
      @TheBospear  4 роки тому

      @@garrfildcsgomore4609 ((_Excel.Range)ws.Cells[i,j]).Value2

  • @saikirangattu2924
    @saikirangattu2924 6 років тому +1

    very easy and simple to use

  • @seveni1423
    @seveni1423 7 років тому

    I have tried to run the code but I get an interop error that excel can't open up the program that I am running. I don't know why it is doing this. Any suggestions?

    • @TheBospear
      @TheBospear  7 років тому

      Hm, there are few possibilities, can you paste the error here so that I can take a look?

    • @seveni1423
      @seveni1423 7 років тому +1

      I got it to work. I think there was an issue with linking to the class itself. I was trying to write a standalone class so I can move this to separate projects. I went back and made the class inside the original project and it worked. So I slowly worked forward and got the functionality that you had and then moved it to a stand alone class and linked to it and it worked. So. Magic.

    • @TheBospear
      @TheBospear  7 років тому

      Yeey. At some point when I get time to continue this tutorial I'll do all necessary things and then make a library out of the class and post it, because I also used original of this class for a bunch of projects.

  • @Adomas_B
    @Adomas_B 4 роки тому

    I did everything as you said but it says that system doesn't find the file although I tied every way to describe a path

    • @TheBospear
      @TheBospear  4 роки тому

      File needs to be in Document folder. Also post the path you're taking for the file so that I can check.

    • @Adomas_B
      @Adomas_B 4 роки тому

      @@TheBospear My path is @"C:\Users\adoma\Documents\Testfile.xlsx";

    • @TheBospear
      @TheBospear  4 роки тому

      @@Adomas_B and in documents folder you have a Testfile.xlsx, not Test.xlsx or Testfile.xls, or variant of that?

    • @Adomas_B
      @Adomas_B 4 роки тому

      @@TheBospear Yes, I have the exactly labeled it 'Testfile' and when I go to properties > security, it says Object name: C:\Users\adoma\Documents\Testfile.xlsx, yet console still throws out an error :
      "System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken = (My 64 bit hash) '. The system cannot find the file specified.'

    • @TheBospear
      @TheBospear  4 роки тому

      @@Adomas_B You might have wanted to lead with the error, it's not excel file that it cannot find, it's your excel interop dll, or more likely, one of it's dependencies. Reinstall Excel and make sure versions match.

  • @diegocarreras9313
    @diegocarreras9313 4 роки тому

    Hi, im getting the following exception:
    'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'
    I have excel version 2011 and it didn't work, installed 2013 afterwards and it still doesn't work, would appreciate any help, thanks!

    • @TheBospear
      @TheBospear  4 роки тому

      Office 365. Or get from nuget. Theres multiple comments here describing that issue and the solution.

  • @kobe_24
    @kobe_24 4 роки тому

    does it work in build?

    • @TheBospear
      @TheBospear  4 роки тому

      The only way for it to work is in build.... did you mean release? In which case yes, release is just a few flags and not building debug files.

  • @StefanSnyman1996
    @StefanSnyman1996 4 роки тому

    Thank you for the video BosPear !
    How do I read a int or double? When i put a number in an excel cell, i get an error "cannot convert double to string". I want to get values from excel and do calculation in my program with the values.

    • @TheBospear
      @TheBospear  4 роки тому +1

      same way you do a string, only replace it with int. So it's int value = (int)ws.ReadCell(0,0);

  • @saidalabed9417
    @saidalabed9417 4 роки тому

    Hi ,
    Complete beginner here. I created a console app and I'm given an error saying "Program does not contain a static main method"

    • @TheBospear
      @TheBospear  4 роки тому

      Main method is an entrance point to any application. In fact using any VS should have generated main method when creating a console application. What's featured in the tutorial however is a Windows Form Application, it too has a main method but it's auto generated in the Program.cs and isn't shown in the video.

    • @saidalabed9417
      @saidalabed9417 4 роки тому

      @@TheBospear Thanks for the replay , i fixed it. However i changed the code a bit. I'm trying to compile the data from all workbooks in a directory to a single worksheet in a blank workbook. The data of each worksheet needs to be appended to the previous data that has been pasted. I looked up the internet and managed to count a worksheet's total rows. But that's not really what i need. Here is the code.
      static void Main(string[] args)
      {
      Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
      Microsoft.Office.Interop.Excel.Workbook sheet = excel.Workbooks.Open(@"C:___________________.xlsx");
      Microsoft.Office.Interop.Excel.Worksheet x = excel.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
      Excel.Range userRange = x.UsedRange;
      int countRecords = userRange.Rows.Count;
      int add = countRecords + 1;
      x.Cells[add, 1] = "TotalRows" + countRecords;
      sheet.Close(true, Type.Missing, Type.Missing);
      excel.Quit();
      }

    • @saidalabed9417
      @saidalabed9417 4 роки тому

      I guess i'm asking for a c# answer to this popular vba question on stackoverflow. stackoverflow.com/questions/43112239/copy-and-paste-data-from-multiple-workbooks-to-a-worksheet-in-another-workbook?rq=1

    • @TheBospear
      @TheBospear  4 роки тому

      @@saidalabed9417 For some reason I didn't get the comment notification. Since you have row numbers, all you need to do is loop through the file names in a folder, loop through the sheets until you find the name, read and write in another file.
      Listing files is done through Directory.GetFiles, while reading sheet names is done with worksheet.Name

  • @eladiogonzalezruiz2112
    @eladiogonzalezruiz2112 4 роки тому

    is this app compatible with Office Excel 2019? I did my Test.xlsx file, my program runs, but does not work, I didn't get the message on the window...

    • @TheBospear
      @TheBospear  4 роки тому

      It's 365, however a lot of versions are on the same standard, so this gives you a place to start, now google excel 2019 interop and find the parallels

    • @eladiogonzalezruiz2112
      @eladiogonzalezruiz2112 4 роки тому

      @@TheBospear I can see that you have first another window that is not "Form1" and after you close this, it shows you "Form1". I only had the "Form1" window that does not show us nothing, do you follow me?... I tried at visual studio 2016 is the same thing...

    • @TheBospear
      @TheBospear  4 роки тому

      @@eladiogonzalezruiz2112 That's a message box window. It's the Messagebox.Show line of code that makes that appear.

    • @eladiogonzalezruiz2112
      @eladiogonzalezruiz2112 4 роки тому

      @@TheBospear Yes I get it, I have this "Messagebox.Show" but still does not appear me when I run it, what problem I have if this happens?

    • @TheBospear
      @TheBospear  4 роки тому

      @@eladiogonzalezruiz2112 One of about a million. Check if the window exists, if not post the code here so I can take a look.

  • @katkovkirill10
    @katkovkirill10 5 років тому +1

    i did everything like you`ve shown but i am getting only this window i.imgur.com/hhordz7.png

    • @JasonACharles
      @JasonACharles 4 роки тому

      Was there a solution to this problem, getting the same thing, not even error code... just Form 1 pops up.

    • @TheBospear
      @TheBospear  4 роки тому

      Put a break point at Messagebox.Show, see if you get the value you expected inside it or if it hits it at all. Form will display the moment everything from the constructor is executed after which Form_Load() is called

  • @fawzysha3ban53
    @fawzysha3ban53 7 років тому

    you really impressive may I know how to get max colomn index & max rows index & max sheet index (I , j , sheet)

    • @TheBospear
      @TheBospear  7 років тому +1

      No such thing, technically (discounting the edge of your ram memory), if you have filled excel sheet that you must loop through and don't know it's size, add a clause of if(string == "")
      For instance
      int i, j = 0;
      while(true)
      {
      string s = excel.ReadCell(i, j);
      if(s == "")
      {
      break;
      }
      else i++;
      }
      That's how you get max i, for max j do the same thing only j++

    • @fawzysha3ban53
      @fawzysha3ban53 7 років тому

      at first thnx for reply
      but I see bug here if user let some index empty cell and continue entering data from the next index I will get only the first occupied cells

    • @TheBospear
      @TheBospear  7 років тому +1

      You can check next 10, or how ever much:
      int i, j = 0;
      int itemp = 0;
      int jtemp = 0
      while(true)
      {
      string s = excel.ReadCell(i, j);
      if(s == "")
      {
      itemp++;
      }
      else i++;
      if(itemp == 10)
      break;
      }
      just change itemp to how ever much you think is proper and check for i.
      There is a predicted way to do it but in personal experience it doesn't work as it should, since what was null value in a cell usually becomes empty string the moment you check the cell.

    • @fawzysha3ban53
      @fawzysha3ban53 7 років тому

      ty sir it works but for sheets program crashes
      int i = 1, j = 1, sheets = 1;
      public void GM()
      {
      int k = 0;
      while(k!=20)
      {
      if (Rcell(i, 1) == "")
      {
      k++;
      i++;
      }
      else
      {
      k = 0;
      i++;
      }
      }
      k = 0;
      while(k!=20)
      {
      if (Rcell(1, j) == "")
      {
      k++;
      j++;
      }
      else
      {
      k = 0;
      j++;
      }
      }
      while (wb.Worksheets[sheets] != null)
      sheets++;
      i -= 21;j -= 21;
      Console.WriteLine("i= " + i + " " + "j= " + j);
      }

    • @TheBospear
      @TheBospear  7 років тому

      Need the error log if you have it, kind of hard to know what happened blind, but a guess is if you try to open sheet 6 out of 5 sheets it will crash, since it tries to open something that is null. So surround it in try and catch and make catch return the number of sheets. Also bad practice to put those variables as global.

  • @totokpatrik4260
    @totokpatrik4260 5 років тому

    Thanks, great video.

  • @beenay18
    @beenay18 2 роки тому

    I don't even know how to get to this point? what type of project should i create? is it c# console project ? or is it winforms project? or is it something else? how to get that excel.cs thing in solution explorer?

    • @TheBospear
      @TheBospear  2 роки тому

      winforms .NetFramework and create new class, name it Excel.cs.

    • @beenay18
      @beenay18 2 роки тому

      @@TheBospear thanks for your reply. I created a new project in VS. selected winforms project in c#. Right clicked the project name in solution explorer and added new class and renamed it excel. Had to google a bit. But i think i am in the right path because the files and code in my project look just like yours now. I created the excel file named Test in my VS project folder. Followed along all the coding. Ran the code. Shows tons of error. Trying to fix the code, uppercase, lowercase, space, underscore what not. Turns out its hard to even copy the code when i dont know what those syntax are doing.

    • @TheBospear
      @TheBospear  2 роки тому

      @@beenay18 Yeah, these tutorials are made for C# devs since years ago Microsoft had little to none documentation on this library.

  • @AdithyakumarCR
    @AdithyakumarCR 4 роки тому

    System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'
    I tried adding Microsoft.Office.Interop.Excel.dll manually from browsing in the reference manager and also via installing using Install-Package from nuget package manager. Still getting the same error. Confused!!
    Please HELP! Thanks.

    • @TheBospear
      @TheBospear  4 роки тому

      You're missing a dependency, install Excel it self.

    • @AdithyakumarCR
      @AdithyakumarCR 4 роки тому

      @@TheBospear Thanks a lot for a quick reply. Didnt expect a reply from you. I figured out what the issue was. I was creating a new project with Console App(.NET CORE), I was supposed to do it with .NET Framework. I just finished with all your videos. It was short and really helpful. Thanks

  • @shirishcin
    @shirishcin 5 років тому +1

    Where are the first steps for creating this project ? unfortunately not helpful for those who want to create from scratch

    • @TheBospear
      @TheBospear  5 років тому +1

      File -> new -> project -> windows form, and name the project, right click in solution explorer add->Class, and name it excel.
      I do suggest that you look in to some basic visual studio tutorials first, this series wasn't made to teach basics of programming but to help out junior developers to work with excel in c#.

  • @Trinable555
    @Trinable555 5 років тому

    Great Video

  • @RobertShane
    @RobertShane 4 роки тому

    I'm getting the error:
    System.IO.FileNotFoundException
    HResult=0x80070002
    Message=Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.
    Source=
    StackTrace:

    • @TheBospear
      @TheBospear  4 роки тому

      Check the file location, with Excel library base location (@"*.xlsx") isn't applocation, it's in Documents folder

    • @RobertShane
      @RobertShane 4 роки тому

      @@TheBospear I don't understand

    • @TheBospear
      @TheBospear  4 роки тому

      @@RobertShane Check the location of the file you are trying to read. It's supposed to be in Documents folder.

    • @RobertShane
      @RobertShane 4 роки тому

      @@TheBospear You mean the excel file I'm trying to read? It has to be in the documents folder?

    • @TheBospear
      @TheBospear  4 роки тому

      @@RobertShane If you're using my code yes, if you want it somewhere else just enter the full path to it in the new Excel("HERE", 1); line

  • @christiangalvan7715
    @christiangalvan7715 7 років тому

    How would you write the code to read through a column of 10 cells? I am not having success.

    • @TheBospear
      @TheBospear  7 років тому

      for(int i = 0; i < 10; i++)
      {
      excel.ReadCell(i, 0);
      }
      You can also select a specific range and read all cells from it, but I will make tutorial on it later, sometime january if nothing else happens. In the meantime here's a stackoverflow link for it:
      stackoverflow.com/questions/2627343/read-all-the-cell-values-from-an-excel-range-in-c-sharp

  • @zadrondraney3905
    @zadrondraney3905 4 роки тому

    I am not sure what is going on but lines 14 and 22 give errors. It may be because I'm using 2019 Visual Studio.

    • @TheBospear
      @TheBospear  4 роки тому

      Doubt it, more likely it's the library version, Microsoft really did a number on interop libraries (hence the need for these videos). What are the errors and what version interop dll are you using?

  • @mhdfirassbarakat6587
    @mhdfirassbarakat6587 4 роки тому

    What Is The "Form1_Load" ?? Please

    • @TheBospear
      @TheBospear  4 роки тому

      Event handler for Form Load event. Do not attempt to just copy the code without basic C# knowledge, you will just give your self a headache. Do a basic C# tutorials first, it shouldn't take more than a week or two, then start making stuff.

  • @robertsmith4019
    @robertsmith4019 2 роки тому

    Where's the first part of this video showing the form and app.config?

    • @TheBospear
      @TheBospear  2 роки тому

      When starting a project in visual studio, you choose a .Net Framework Form, and you get what's on the start of the video

  • @afsanarabeya4417
    @afsanarabeya4417 7 років тому

    There is a error what says "Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.Binder.Convert' " .what do to ?

    • @TheBospear
      @TheBospear  7 років тому

      Check References for Microsoft.CSharp reference, if it's there remove it then add it back if it's not just add it. That error is always tied to Microsoft.CSharp.dll as far as I've seen.

    • @afsanarabeya4417
      @afsanarabeya4417 7 років тому

      thank u but it's not working.when I added again ,errors were gone. after debugging again, Error appears :(

    • @TheBospear
      @TheBospear  7 років тому

      Strange. Are you using any dynamic calls?

  • @venkataramananori5579
    @venkataramananori5579 4 роки тому

    I'm getting an Error 1 No overload for method 'Open' takes '1' arguments

    • @TheBospear
      @TheBospear  4 роки тому

      What version of interop are you using and also can you paste your excel class code here so I can take a look?

  • @christiandanielmoralesboho4263
    @christiandanielmoralesboho4263 4 роки тому

    hello, how can I close excel after use it, in my task manager appears it after close program, thank you.

  • @kamanyuhuhu9985
    @kamanyuhuhu9985 4 роки тому

    Sir, i have a problem when i called int data from the excel, maybe you can help me

    • @TheBospear
      @TheBospear  4 роки тому

      I'm going to need more info than that. Where does it break, what's the error message and your code snippet from the method where it breaks

  • @donstz
    @donstz 4 роки тому

    What If I have Microsoft.Office.Interop.Excel -Version 14? There is no property Value2

    • @TheBospear
      @TheBospear  4 роки тому

      Value, Text etc.

    • @donstz
      @donstz 3 роки тому

      @@TheBospear Couldn't find any way. Finally NuGet LinqToExcel did the job