77

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
  • 98,240
  • 88
  • 296
  • 433
tksy
  • 3,429
  • 17
  • 56
  • 61
  • 1
    So what's the problem? Please describe it since it's easier to see directly than start creating a blank project myself and then copy and paste your code. – Mats Fredriksson Jan 21 '09 at 11:35
  • for starts the directory part is throwing an error 'system.io.directory is a type but used like a variable" – tksy Jan 21 '09 at 11:48
  • This would have stopped that error: if(!Directory.Exists(@"C:\csharp\error report.xls")) – dkroy Mar 29 '13 at 13:20
  • 2
    if (Directory("C:\\csharp\\error report1.xls") = "") should be if (!File.Exists("C:\\csharp\\error report1.xls")) – Stephen MacDougall Oct 11 '13 at 19:09

11 Answers11

103

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • @Saravanan: See [MSDN](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbooks.open.aspx): `Object ReadOnly`. I guess you need to pass `true`. – abatishchev Jan 18 '12 at 07:26
  • :Please See my Question... http://stackoverflow.com/questions/8906670/how-to-open-excel-file-in-c-sharp-winform-application-with-read-only-protection – Saravanan Jan 18 '12 at 07:42
  • when I add that I get error as `CS0104: 'DataTable' is an ambiguous reference between 'System.Data.DataTable' and 'Microsoft.Office.Interop.Excel.DataTable'` – Nad Apr 13 '16 at 05:24
  • @coder: remove `using System.Data;` or use "`using DataTable = Microsoft.Office.Interop.Excel.DataTable;` – abatishchev Apr 13 '16 at 05:27
  • @abatishchev: when I remove `using System.Data;` i get namespace error for `dataset` which I am using for another set of code.. – Nad Apr 13 '16 at 05:30
  • @coder: use full name (namespace.class.name) in either case – abatishchev Apr 13 '16 at 05:31
  • when I write `System.Data.DataTable ObjDt = ObjPriDal.ExecuteSystem.Data.DataTable(strquery);` it gives error for `ExecuteSystem` as **DataAccessLayer does not contain a definition for `ExecuteSystem`** – Nad Apr 13 '16 at 05:34
  • @coder: you don't need it in the right expression. Use full name as you usually declare variable's type – abatishchev Apr 13 '16 at 05:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/108998/discussion-between-coder-and-abatishchev). – Nad Apr 13 '16 at 05:38
  • @abatishchev: I tried like this `var directory = Server.MapPath("~/Attachment/"); ExcelLibrary.DataSetHelper.CreateWorkbook(directory + "Employee_lwpc_Details.xls", DS_lwpc); Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(directory + "Employee_lwpc_Details.xls", DS_lwpc));` getting error as **cannot implicitly convert type Microsoft.Office.Interop.Excel to Excellibrary.office.Excel.Workbook** – Nad Apr 13 '16 at 05:46
  • @abatishchev I tested your code, it's running. I'm wondering though, how is it possible to instantiate Application when it is actually an interface? – ThomasMX Jun 06 '16 at 19:43
  • @ThomasMX: I was wondering this for a while too. Since VSO is a COM wrapper, .NET makes it possible to instantiate an interface. Each is decorated with Guid and that's how it's being read from registry and instantiated. – abatishchev Jun 06 '16 at 20:04
  • See here for a full example of creating and saving an Excel file using the interop https://stackoverflow.com/a/23102523/8595398 – Matthew May 29 '19 at 03:17
62
FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
    System.Diagnostics.Process.Start(@"C:\test\report.xlsx");
}
else
{
    //file doesn't exist
}
Community
  • 1
  • 1
Mennan
  • 4,451
  • 13
  • 54
  • 86
  • Works for me. Certainly simpler than the accepted 2009 answer because no additional tools are needed, and it is essential a one-liner. – Roland Jan 09 '19 at 16:19
  • 1
    Great, just what I was looking for, thanks! I simplified it by just passing the fi inside the start as `System.Diagnostics.Process.Start(fi.ToString());` – Eda Dec 15 '20 at 09:23
  • 1
    This is by far, the most easy way to do it. Thank you – shahsani Jul 13 '21 at 05:08
  • This is the best solution. However in .NET core it has to be done a bit differently: https://stackoverflow.com/a/60970719/1018443 – nharrer Aug 15 '22 at 10:04
11
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
  • 80,625
  • 14
  • 153
  • 225
Flane
  • 111
  • 1
  • 3
4

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

3

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

rudenaggar
  • 61
  • 1
3

For opening a file, try this:

objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.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#.

G S
  • 35,511
  • 22
  • 84
  • 118
2

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.

Mats Fredriksson
  • 19,783
  • 6
  • 37
  • 57
2
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
  • 2,092
  • 4
  • 37
  • 62
Jairaj
  • 21
  • 1
1

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

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
bvgheluwe
  • 853
  • 7
  • 25
1

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
  • 1,406
  • 2
  • 12
  • 21
1

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.

Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176