I want to get only active sheet name from excel file using c#,but now i am getting all the sheet names,how can i get only active sheet name from excel using c#?
you can use the ActiveSheet property to get the name out of it
See link here http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.activesheet
e.g.
WorkSheet sheet = (WorkSheet)_application.activesheet;
string name = sheet.Name;
You may want to use NugetPackage Library NPOI (https://archive.codeplex.com/?p=npoi).
You can retrieve lots of useful information about Excel files (XLSX or XLS). Including the active worksheet when the workbook was saved (ActiveSheetIndex property).
It has the advantage of not relying on Microsoft Interpot API (not requiring Excel to be installed).
You may try this:
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
...
//Stream
FileStream arquivoXLSX = new FileStream(XLSXWorkbokPath, FileMode.Open, FileAccess.Read);
//Workbook Data from XML
XSSFWorkbook workbook = new XSSFWorkbook(XLSXWorkbokPath);
//Active Worksheet Index
var ActWsIndex = workbook.ActiveSheetIndex;
//Active Worksheet Name
var ActWsName = workbook.GetSheetName(ActWsIndex);
I hope it helps.
Related
I have an open instance of Excel which is already connected to via a COM process, which I have changed the value of one of the cells. In C# I can't get a connection to the sheet, but in python i can
Working Python code:
import xlwings as xw
wb = xw.Book('c:/users/me/Desktop/mysheet.xlsx')
sheet = wb.sheets['Sheet1']
print(sheet.range('B1').value) # returns the current value
Non-working C# code:
var xlApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Workbook wb = xlApp.ActiveWorkbook; // returns null
Worksheet excelSheet = wb.ActiveSheet;
string test = excelSheet.Cells[1, 2].Value.ToString();
Is there a way to get C# to connect to this sheet, given it is already open via a COM automation from another software product?
Most of the online discussion around GetActiveObject is to talk to a specific instance of Excel if there are multiple instances running, I have the opposite problem, a single instance of Excel and multiple applications trying to connect to it.
Workbook wb = System.Runtime.InteropServices.Marshal.BindToMoniker(#"c:\users\me\Desktop\mysheet.xlsx") as Workbook;
should get the workbook even if it is already opened in Excel or not.
https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/
I am accessing data from an embedded excel sheet through c#, but in order for the script to read the excel sheet I must manually press "enable macros" every time. How can I write a script such that it automatically enables macros every time? I am opening various excels so cannot change the settings on the excel sheet itself.
I saw something regarding the use of VBA but am unsure what to do? Would using this reference (using VBA = Microsoft.Vbe.Interop) be helpful?
The code below simply opens the excel, but I still have to click enable macros.
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
wordApp = new Word.Application();
xlApp = new Excel.Application();
wordDoc = wordApp.Documents.Open(#"Y:DocumentName");
Word.InlineShapes ils = wordDoc.InlineShapes;
ils[1].OLEFormat.Activate();
xlWorkBook = ils[1].OLEFormat.Object;
Have you tried setting the DisplayAlerts property to false?
xlApp.DisplayAlerts = false;
I am using the COM to work with Excel 2007. When I use the following code, it opens to the first sheet by default.
Excel = Sys.OleObject("Excel.Application");
Delay (3000); // Wait until Excel starts
Excel.Visible = true;
Excel.Workbooks.Open("G:\\Documentation\\CalCit Excel Files\\2004 Test Data v3 FINAL_new.xlsx");
I need to select different sheets. I tryed using the following code from the DDTdriver code.
Excel = Sys.OleObject("Excel.Application");
Delay (3000); // Wait until Excel starts
Excel.Visible = true;
Excel.Workbooks.Open("G:\\Documentation\\CalCit Excel Files\\2004 Test Data v3 FINAL_new.xlsx", "sheet2", true);
But this does not work. I have tryed many other configs and still get nothing.
For Excel version 2013 or later :
According to learn.microsoft.com
this can be done with Sheets.Select method :
((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Select();
which in the code the selected sheet is 1
another method for older versions of Excel :
Excel.Worksheet sheet = (Excel.Worksheet)this.Sheets["Sheet2"];
sheet.Select(Type.Missing);
where Sheet2 is the name of the sheet
Given the following scenario:
I have a source.xlsx file with multiple worksheets (worksheet1, worksheet2, workshToCopy, etc) and I generate the destination.xlsx based on another .xlsx template file that has different worksheets than the source.xlsx. I want to add a worksheet from the source file to the destination file.
For now I was able to add an empty worksheet to my destination file like this:
if (FileExists(outputFile) && FileExists(inputFile))
{
var inputPackage = new ExcelPackage(inputFile);
var outputPackage = new ExcelPackage(outputFile);
var summaryInputWorksheet = inputPackage.Workbook.Worksheets[ExcelSummaryHelper.SummaryWorksheet];
outputPackage.Workbook.Worksheets.Add(summaryInputWorksheet.Name);
outputPackage.Workbook.Worksheets.MoveToEnd(summaryInputWorksheet.Name);
outputPackage.Save();
}
What's the best approach to copy the content of workshToCopy from source.xlsx to destination.xlsx's new worksheet using the EPPlus library ?
Solved.
There's an overload for the Add method on the ExcelWorksheets class that looks like this:
ExcelWorksheets.Add(string Name, ExcelWorksheet Copy)
Can't believe I haven't seen it.
Couldn't you just clone the existing one?
ExcelWorksheets clonedWorksheet = currentExcelWorksheet.Clone();
I'm writing a program to process some excel documents, the program is written in C# in Visual Studio 2010, and I'm using the NPOI library.
I notice the I was not able to use CloneSheet() for the xlsm file, but I was able to do so with xlsx.
CloneSheet() is a function that I really need for the process, so I really would like to get it working instead of copy everything cell by cell.
I thought of converting the file to xlsx. I was able to do it manually, but not programmatically.
This is the code I wrote to attempt to do so:
XSSFWorkbook workbook;
//read original xlsm file into workbook
using (FileStream file = new FileStream(#"OriginalFile\" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }
//change file extension to xlsx and save in a new location
filename = Path.ChangeExtension(filename, "xlsx");
if (!Directory.Exists("NewFile"))
Directory.CreateDirectory("NewFile");
FileStream stream = new FileStream(("NewFile\\New" + filename), FileMode.Create, System.IO.FileAccess.Write);
workbook.Write(stream);
stream.Close();
//read the newly created file from the new location
using (FileStream file = new FileStream(#"NewFile\\New" + filename, FileMode.Open, FileAccess.Read))
{ workbook = new XSSFWorkbook(file); }
The above code will create the new xlsx file, but the file cannot be open and seems to be corrupted...
I've been googling for a while and couldn't seem to find a solution, can anyone help or point me to the right direction?
--EDIT---
I tried a different method using Open XML I found here, but I have the same issue, where the file is created but I can't open the file.
However, the file doesn't seem to be corrupted. My program that is reading the file have no problem reading the data, and when I try to open the file in excel it's saying "The file is a macro-free file, but contains macro-enable content."
Seems like I'm getting closer, but I need to be able to open the output file otherwise it's no use....
You may have to roll your own method: iterate rows then cells. This post Copy Row Helper got me started. You'll have to modify it to use two workbooks. This method will copy data and formulas. CellStyles will have to be recreated as they they specific to the originating workbook.