Hi friends,
I am beginner for using Excel. I need to figure out how to find the selected sheet name from the workbook in Excel.
Thanks a lot.
Devaraj
This is a little old. In 2004, but I used it and it helped me. What I understand is you want to call a certain excel sheet to your c# app? Anyway, check this site out, it will help if thats what your doing.
C# - Retrieve Excel Workbook Sheet Names.
You can use this solution ....
Taken from here ....using excel oledb to get sheet names in sheet order
private Dictionary<int,string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int,string> excelSheets = new Dictionary<int,string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
{
_workBook.Close(false, Type.Missing, Type.Missing);
}
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
Application xlsxApp;
string sheetname = (xlsxApp.ActiveSheet).Name;
Here is a more up to date answer:
Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
string activeWorksheetName = activeWorksheet.Name;
hth
Related
First of all in my code im opening an excel sheet and reading it into a list. Second of all im closing this excel sheet and creating a new excel sheet:
excel_init("C:\\Users\\oma\\Desktop\\excel2.xlsx"); // this path does NOT exist yet
Next its going to this method:
static void excel_init(String path)
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (System.IO.File.Exists(path))
{
// then go and load this into excel
newWorkbook_First = appExcel.Workbooks.Open(path, true, true);
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
}
else
{
try
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
appExcel.Visible = true;
newWorkbook_First = appExcel.Workbooks.Add(1);
objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook_First.Sheets[1];
objsheet.Name = ("test");
var newSheet3 = (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
newSheet3.Name = "test2";
var newSheet2 = (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
newSheet2.Name = "test3";
}
catch (Exception e)
{
Console.Write("Error");
}
finally
{
}
}
}
It wont create excel2.xlsx on my desktop, why not?
Next in my main I am shouting excel_setValue this way:
excel_setValue("C", "hello", "");
This is the excel_setValue function:
static void excel_setValue(string cellname, string value, string color)
{
objsheet.get_Range(cellname).set_Value(Type.Missing, value);
if (kleur == "red")
{
objsheet.get_Range(cellname).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
}
How do I add the sheet to this? For exmaple: excel_setValue(cellname, value, color, sheetname)
Finally I do excel_close();
the excel_close function:
static void excel_close()
{
if (appExcel != null)
{
try
{
newWorkbook_First.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook.ActiveSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
objsheet = null;
}
catch (Exception ex)
{
appExcel = null;
Console.WriteLine("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
It closes and ask me if I wanna save/not-save or cancel it. And it will save # documents with no errors given
I create my Excel like this worked fine for me!
You need to do the folowing in you code before the newWorkbook_First.close(); part:
newWorkbook_First.SaveAs(totalPath);
I hope this will help you solve the problems..
using Excel = Microsoft.Office.Interop.Excel;
internal static bool ExportDGV(DataGridView DGV, List<string> selectedCustomerList, string path, string fileName, string exportName, int exportType, string mailSubject)
{
string totalPath;
//Create an Excel application instance
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Application.Workbooks.Add();
Excel._Worksheet worksheet = null;
excelApp.Visible = false;
worksheet = excelWorkBook.ActiveSheet;
//set headers
for (int i = 1; i < DataGridView.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGV.Columns[i - 1].HeaderText;
}
createList(worksheet, DGV);
//Create excel with the choosen name
Worksheet sheet1 = excelWorkBook.Worksheets[1];
worksheet.Name = fileName;
totalPath = path + "/" + fileName + ".xlsx";
//if path exist add a number
totalPath = directoryExist(totalPath, path, fileName);
//Save exel and Quit exelApp
excelWorkBook.SaveAs(totalPath);
excelWorkBook.Close();
excelApp.Quit();
}
You can use EpPlus library for excel. It is very easy to use and well documented. You don't need to use COM classes anymore
Hi i have written code using the Microsoft.Office.Interop.Excel dll but it is not supported online when i published my website. I then found the EPPlus dll witch is supported online but i am having troubles converting the code to use this new dll.
Old Code useing Interop.Excel:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[8];
public void ToSpreadSheet()
{
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(tempFolderPathAlt + "dvforms\\InvestecTemplate.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet[0] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet[1] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
xlWorkSheet[2] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
xlWorkSheet[3] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);
xlWorkSheet[4] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(5);
xlWorkSheet[5] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(6);
xlWorkSheet[6] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(7);
xlWorkSheet[7] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(8);
}
This worked great but now i need to use the EPPlus dll and i'm having problems.
using Excel = OfficeOpenXml;
Excel.ExcelPackage xlApp;
Excel.ExcelWorkbook xlWorkBook;
Excel.ExcelWorksheet[] xlWorkSeet = new Excel.ExcelWorksheet[8];
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(tempFolderPathAlt + "dvforms\\InvestecTemplate.xlsx");
Excel.ExcelPackage xlApp = new Excel.ExcelPackage(stream);
//This is where the problems begin, xlWorkBook.Worksheets.Add(1) is all underlined in red.
xlWorkSeet[0] = (Excel.ExcelWorksheet)xlWorkBook.Worksheets.Add(1);
How do i load the work sheets from my Excel template? I am unsure if i have done the above correctly, Please help i need it badly.
Thanks in advance.
FileInfo existingFile = new FileInfo(filePath);
using (var package = new ExcelPackage(existingFile))
{
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
int i = 0;
foreach(ExcelWorksheet worksheet in workBook.Worksheets)
{
xlWorkSeet1[i] = worksheet;
i = i + 1;
}
}
}
The function Add() takes in a string parameter that's the name of your worksheet. Try:
xlWorkSeet[0] = (Excel.ExcelWorksheet)xlWorkBook.Worksheets.Add("Sheet1");
I am working on writing the data into Excel sheet in c#.
I have wriiten the following code.
string excel_filename = #"C:\Users\Downloads\bookmain.xlsx";
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook wb = excel.Workbooks.Open(excel_filename);
Excel.Worksheet sh = wb.Sheets.Add();
sh.Name = "TestSheet";
sh.Cells[1, "A"].Value2 = "SNO";
sh.Cells[1, "B"].Value2 = "Name";
sh.Cells[1, "C"].Value2 = "ID";
for (int i = 0; i < 2; i++)
{
sh.Cells[i+2, "A"].Value2 = "1";
sh.Cells[i+2, "B"].Value2 = "A";
sh.Cells[i+2, "C"].Value2 = "1122";
}
wb.Save();
excel.Quit();
Here I have given the path of excel file that already exists and it is empty.
How to change this code that, when i give the path it should automatically check, if it exists it have to create otherwise no need to create.
Even my code also need to check sheet name, it it exist i shall directly edit it or else I need to create a new sheet.
Can any one share their response.
Thank you.
for checking existence of file :
if(!File.Exists(excel_filename))
{
//if not exists then only create:-
}
and for checking worksheet you can do like :
foreach (Sheet sheet in workbook.Sheets)
{
if (sheet.Name.equals("Test"))
{
//do something
}
}
UPDATED :
this is how it works :
Create Excel object
Excel.Application excel = new Excel.Application();
make Excel visible
excel.visible = true
add a worksheet
Excel.Worksheet sh = wb.Sheets.Add();
save it as
wb .SaveAs( #"C:\Users\Downloads\bookmain.xlsx",
Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
I have an excel workbook opened via double-clicking it in windows explorer but cannot access it in code
Excel.Application xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbooks xlBooks = xlApp.Workbooks;
xlBooks.Count equals 0, why isn't it referencing my opened workbook?
EDIT
Here are the various scenarios and what is happening:
Scenario 1: If the file is not already open
Code opens workbook, I am happy.
Scenario 2: If the file is initially opened from code and I close and reopen the app
Code references file just fine xlBooks.Count equals 1, I am happy.
Scenario 3: If the file is initially opened not from code, and via double-clicking it in explorer
Code opens another instance of the file xlBooks.Count equals 0, I am in a rage!
Here is the entire code as it stands right now
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
public class ExcelService : IExcelService
{
const string _filePath = #"C:\Somewhere";
const string _fileName = #"TestFile.xlsb";
string _fileNameAndPath = Path.Combine(_filePath, _fileName);
Application xlApp;
Workbooks xlBooks;
Workbook xlBook;
Worksheet xlSheet;
public ExcelService()
{
try
{
xlApp = (Application)Marshal.GetActiveObject("Excel.Application");
xlBooks = xlApp.Workbooks;
var numBooks = xlBooks.Count;
Log.Info("Number of workbooks: {0}".FormatWith(numBooks));
if (numBooks > 0)
{
xlBook = xlBooks[1];
Log.Info("Using already opened workbook");
}
else
{
xlBook = xlBooks.Open(_fileNameAndPath);
Log.Info("Opening workbook: {0}".FormatWith(_fileNameAndPath));
}
xlSheet = (Worksheet)xlBook.Worksheets[1];
// test reading a named range
string value = xlSheet.Range["TEST"].Value.ToString();
Log.Info(#"TEST: {0}".FormatWith(value));
xlApp.Visible = true;
}
catch (Exception e)
{
Log.Error(e.Message);
}
}
~ExcelService()
{
GC.Collect();
GC.WaitForPendingFinalizers();
try
{
Marshal.FinalReleaseComObject(xlSheet);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlBook);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlBooks);
}
catch { }
try
{
Marshal.FinalReleaseComObject(xlApp);
}
catch { }
}
}
I know this thread is a little old, but I found another way of doing this. When you create a new Excel.Applicationobject you have to create the WorkBooks object. When you access an already opened Excel file, the WorkBooks object is already created, so you just need to add a new WorkBook to the existing one. #Tipx 's solution works great if you have access to the WorkBook name, but in my case the current WorkBook name is always random. Here's the solution I came up with to get around this:
Excel.Application excelApp = null;
Excel.Workbooks wkbks = null;
Excel.Workbook wkbk = null;
bool wasFoundRunning = false;
Excel.Application tApp = null;
//Checks to see if excel is opened
try
{
tApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
wasFoundRunning = true;
}
catch (Exception)//Excel not open
{
wasFoundRunning = false;
}
finally
{
if (true == wasFoundRunning)
{
excelApp = tApp;
wkbk = excelApp.Workbooks.Add(Type.Missing);
}
else
{
excelApp = new Excel.Application();
wkbks = excelApp.Workbooks;
wkbk = wkbks.Add(Type.Missing);
}
//Release the temp if in use
if (null != tApp) { Marshal.FinalReleaseComObject(tApp); }
tApp = null;
}
//Initialize the sheets in the new workbook
Might not be the best solution but it worked for my needs. Hope this helps someone. :)
If all your workbooks are opened in the same Excel instance (you can check this by checking if you can switch from one to the other using Alt-tab). You can simply refer to the other using Workbooks("[FileName]"). So, for example :
Dim wb as Workbook //for C#, type Excel.Workbook wb = null;
Set wb = Workbooks("MyDuperWorkbook.xlsx") //for C#, type wb = Excel.Workbooks["MyDuperWorkbook.xlsx"];
wb.Sheets(1).Cells(1,1).Value = "Wahou!"
I'm trying to delete a worksheet from a excel document from a .Net c# 3.5 application with the interop Excel class (for excel 2003).
I try many things like :
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
worksheet.Delete();
It's doesn't work and doesn't throw any error ...
After more than one hour looking I found the answer:
xlApp.DisplayAlerts = false;
worksheet.Delete();
xlApp.DisplayAlerts = true;
When dealing with deleting Excel Worksheets, there are two important things to know:
Excel interop counts from 1 (and not from zero), therefore, removing the second item will cause the third item to take its place!. so, the proper way to remove worksheets is from the last to the first:
// Remove LAST worksheet
MyWorkBook.Worksheets[3].Delete();
// and only then remove the second (which is the last one)
MyWorkBook.Worksheets[2].Delete();
alternatively, you can delete the second item ([2]) on the list twice, which will give you the same result.
The following line will throw exception when you only got one worksheet left:
MyWorkBook.Worksheets[1].Delete();
It is also important to note that the workbook must contain at least one worksheet; this means you cannot delete all worksheets in a workbook.
Microsoft.Office.Interop.Excel.Worksheet worksheet = Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets[1];
worksheet.Delete();
Try to find worksheet by name:
var app = new Microsoft.Office.Interop.Excel.Application();
var workbook = app.Workbooks.Add();
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets["Sheet3"]).Delete();
we can delete the work sheet like this
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return;
}
xlApp.DisplayAlerts = false;
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
+ "\\Sample.xlsx";
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets worksheets = xlWorkBook.Worksheets;
worksheets[4].Delete();
worksheets[3].Delete();
xlWorkBook.Save();
xlWorkBook.Close();
releaseObject(worksheets);
releaseObject(xlWorkBook);
releaseObject(xlApp);
and use this
static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
throw ex;
}
finally
{
GC.Collect();
}
}
We delete excel worksheets from a c# console application like this:
Microsoft.Office.Interop.Excel.Worksheet worksheet =
(Worksheet)workbook.Worksheets["Worksheet_Name" (or) "Countings"];
worksheet.Delete();