Release Interop Excel object - c#

I'm currently writting a C#.NET application who use a VBA macro in an Excel file.
I run the macro from the c# application when the user click on a button. I have to wait all data are downloaded that's why this is the VBA code who execute "Application.Quit".
There is my code :
private void toolStripButton5_Click(object sender, EventArgs e)
{
int lastUsedRowFund, lastUsedRowEquity, lastUsedRowBond, lastUsedRowAccount = 0;
Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook oWB = null;
Excel.Worksheet oSheetFund = null;
Excel.Worksheet oSheetEquity = null;
Excel.Worksheet oSheetBond = null;
Excel.Worksheet oSheetAccount = null;
oXL.Visible = false;
oWB = oXL.Workbooks.Open("C:\\extract.xlsm");
oSheetFund = oWB.Sheets["Fund"];
oSheetEquity = oWB.Sheets["Equity"];
oSheetBond = oWB.Sheets["Bond"];
oSheetAccount = oWB.Sheets["Account"];
string[] valuesHeaderFund = {"field1", "field2" };
string[] valuesHeaderEquity = {"field1", "field2"};
string[] valuesHeaderBond = {"field1", "field2"};
string[] valuesHeaderAccount = {"field1", "field2"};
Excel.Range headerFund = oSheetFund.get_Range("A1", "AA1");
Excel.Range headerEquity = oSheetEquity.get_Range("A1", "AE1");
Excel.Range headerBond = oSheetBond.get_Range("A1", "AE1");
Excel.Range headerAccount = oSheetAccount.get_Range("A1", "AE1");
headerFund.Value2 = valuesHeaderFund;
headerEquity.Value2 = valuesHeaderEquity;
headerBond.Value2 = valuesHeaderBond;
headerAccount.Value2 = valuesHeaderAccount;
Excel.Range lastRowFund = oSheetFund.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowEquity = oSheetEquity.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowBond = oSheetBond.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range lastRowAccount = oSheetAccount.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
lastUsedRowFund = lastRowFund.Row;
lastUsedRowEquity = lastRowEquity.Row;
lastUsedRowBond = lastRowBond.Row;
lastUsedRowAccount = lastRowAccount.Row;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string[] data = { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString()};
if (row.Cells[5].Value.ToString() == "FON")
{
lastUsedRowFund += 1;
oSheetFund.get_Range("A" + lastUsedRowFund, "K" + lastUsedRowFund).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACT")
{
lastUsedRowEquity += 1;
oSheetEquity.get_Range("A" + lastUsedRowEquity, "K" + lastUsedRowEquity).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "OBL")
{
lastUsedRowBond += 1;
oSheetBond.get_Range("A" + lastUsedRowBond, "K" + lastUsedRowBond).Value2 = data;
}
else if (row.Cells[5].Value.ToString() == "ACCOUNT")
{
lastUsedRowAccount += 1;
oSheetAccount.get_Range("A" + lastUsedRowAccount, "K" + lastUsedRowAccount).Value2 = data;
}
}
RunMacro(oXL, new Object[] { "Main" });
oXL.UserControl = false;
//oWB.Close();
//oXL.Quit();
releaseObject(lastRowFund);
releaseObject(lastRowEquity);
releaseObject(lastRowBond);
releaseObject(lastRowAccount);
releaseObject(headerFund);
releaseObject(headerEquity);
releaseObject(headerBond);
releaseObject(headerAccount);
releaseObject(oSheetFund);
releaseObject(oSheetEquity);
releaseObject(oSheetBond);
releaseObject(oSheetAccount);
releaseObject(oWB);
releaseObject(oXL);
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
When i click on the toolStripButton5, everything is working. But at the end an "EXCEL.EXE" processus still alive in task manager. When i click again on the button, a new "EXCEL.EXE" is create but when the task is finish, the processus is correctly release.
When i quit my application, the first processus is release.
Can you help me to correctly release the object at the first click.
Regards,
Danny.

Unfortunatelly this is not so simple to quit Excel app, because COM objects of Interoop services still exists in memory. That's why Excel.exe process is still running. Every object can be released using Marshal class. Sample codes:
Marshal.ReleaseComObject(excelSheets); //Worksheet
Marshal.ReleaseComObject(excelSheet); //Sheet
...and so on.
Hope this helps.

Now, it works greatly. When i execute a second extraction with Excel, the first process is correctly release when the new one is created.
I just replace in "releaseObject" System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); by
Marshal.ReleaseComObject(obj);
Maybe because i use "using System.Runtime.InteropServices;" in the header.
Thanks a lot.
Regards

Related

Display and read an Excel file into a datagridview

I have successfully displayed the data using a code I found at this particular website. The problem is, the colour, bold or italics of the font isn't carried over. I need to read the code of a specific cell and convert it into a HTML string and display it as a textbox elsewhere. So I really need to learn how to import colour, bold or italics so I can convert it too. I will be eternally grateful to any kind soul who helps me on this one. Below is my current code.
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [sheet1$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
The following opens an Excel file in the app folder, get cell value, fore color, see if bold and italic is set for range sheet1 cell H2. Please note there is a decent amount of code which is warranted so that all objects used here are released upon finishing our work.
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1_CS
{
public class ExcelCode
{
public System.Drawing.Color ForeColor;
public ExcelCode() { }
public string GetCellValue(
string FileName,
string SheetName,
string CellAddress)
{
string CellValue = "";
if (System.IO.File.Exists(FileName))
{
bool Proceed = false;
Excel.Application xlApp = null;
Excel.Workbooks xlWorkBooks = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Sheets xlWorkSheets = null;
Excel.Range xlCells = null;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(FileName);
xlApp.Visible = false;
xlWorkSheets = xlWorkBook.Sheets;
for (int x = 1; x <= xlWorkSheets.Count; x++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];
if (xlWorkSheet.Name == SheetName)
{
Proceed = true;
break;
}
System.Runtime.InteropServices
.Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkSheet = null;
}
if (Proceed)
{
xlCells = xlWorkSheet.Range[CellAddress];
try
{
Console.WriteLine("Bold: {0}", xlCells.Font.Bold); // bool
Console.WriteLine("Italic: {0}", xlCells.Font.Italic); // bool
ForeColor = System.Drawing.ColorTranslator.FromOle((int)xlCells.Font.Color);
CellValue = Convert.ToString(xlCells.Value);
}
catch (Exception)
{
// Reduntant
CellValue = "";
}
}
else
{
MessageBox.Show(SheetName + " not found.");
}
xlWorkBook.Close();
xlApp.UserControl = true;
xlApp.Quit();
ReleaseComObject(xlCells);
ReleaseComObject(xlWorkSheets);
ReleaseComObject(xlWorkSheet);
ReleaseComObject(xlWorkBook);
ReleaseComObject(xlWorkBooks);
ReleaseComObject(xlApp);
}
else
{
MessageBox.Show("'" + FileName +
"' not located. Try one of the write examples first.");
}
return CellValue;
}
public static void ReleaseComObject(object obj)
{
try
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception)
{
obj = null;
}
}
}
}
Form code which works from a button and has a panel
var demoExcel = new ExcelCode();
// open an Excel file in the app folder, get information from H2 in Sheet1
textBox1.Text = demoExcel
.GetCellValue(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demo.xlsx"),
"Sheet1",
"H2");
// Form has a panel, set back color to Sheet1.H2 color
panel1.BackColor = demoExcel.ForeColor;
// Translate the color to HTML
var htmlColor = System.Drawing.ColorTranslator.ToHtml(demoExcel.ForeColor);
Console.WriteLine(htmlColor.ToString());

C# not creating the excel file and cannot write in different excel sheets

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

Export To Excel C# Error

I don't get the error that appears in my export to excel code. I have this error
Unable to cast COM object of type 'System.__ComObject' to interface
type 'Microsoft.Office.Interop.Excel.Range'. This operation failed
because the QueryInterface call on the COM component for the interface
with IID '{00020846-0000-0000-C000-000000000046}' failed due to the
following error: No such interface supported (Exception from HRESULT:
0x80004002 (E_NOINTERFACE)).
Here is the code in my gridview, my gridview's name is dgvCommission.
void worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_elapsed);
timer.Start();
Invoke(new MyDelegate(ShowLabel), "Loading...");
BACS.DateFrom = this.dtFrom.Value.ToShortDateString(); //this.dtFrom.Text;
BACS.DateTo = this.dtTo.Value.ToShortDateString(); //this.dtTo.Text;
BACS.BrokerAgent = BrokerXML;
BACS.Payor = PayorXML;
DS = BACS.GET_SP_BACS_ComputeCommission();
ReadData(DS, this.dgvCommision);
CheckGrid();
Thread.Sleep(1);
timer.Stop();
}
catch
{ }
}
And here is my export to excel code in my form.
private void ExportToExcel()
{
string[] arrays = new string[19];
arrays[0] = "Type";
arrays[1] = "Broker Agent";
arrays[2] = "Payor";
arrays[3] = "Billing #";
arrays[4] = "OR No.";
arrays[5] = "OR Date";
arrays[6] = "Particulars";
arrays[7] = "Mode";
arrays[8] = "Amount Billed";
arrays[9] = "Amount Paid";
arrays[10] = "Non Comm Items";
arrays[11] = "Net";
arrays[12] = "Output VAT";
arrays[13] = "Commissionable Amount";
arrays[14] = "WTAX Rate";
arrays[15] = "WTAX";
arrays[16] = "Net Commission";
arrays[17] = "InputVAT";
arrays[18] = "For Fund Release";
SystemUtil.ExportToExel(DS, arrays);
}
ExportToExcel class code is this:
public void ExportToExel(DataSet ds,string[] arrays)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "EXCEL";
DataTable dt2 = new DataTable();
if (ds.Tables[0] != null)
{
dt2 = ds.Tables[0];
}
int rowCount = 1;
foreach (DataRow dr in dt2.Rows)
{
rowCount += 1;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = arrays[i - 1];// dt.Columns[i - 1].ColumnName;
// oSheet.Cells[1,i].Font.Background = System.Drawing.Color.Red;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
////// Resize the columns
//oRange = oSheet.get_Range(1, 23);
////oRange.EntireColumn.AutoFit();
//oRange.Range[1, 2].AutoFit();
// Save the sheet and close
oSheet = null;
// oRange = null;
//oWB.SaveAs(#"c:\REPORTS.xls", Excel.XlFileFormat.xlWorkbookNormal,
// Missing.Value, Missing.Value, Missing.Value, Missing.Value,
// Excel.XlSaveAsAccessMode.xlExclusive,
// Missing.Value, Missing.Value, Missing.Value,
// Missing.Value, Missing.Value);
//oWB.Close(Missing.Value, Missing.Value, Missing.Value);
//oWB = null;
//oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
The exception error pops up in this code. oSheet.Cells[1, i] = arrays[i - 1];
Do you guys know how can this happen? I don't understand what's wrong in my code.. Please help me on this one. Thanks in advance for your help.
Try changing
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
To
oSheet = (Excel.Worksheet)oXL.ActiveSheet;
Further explanation: MSDN provides the following note regarding the Workbook Interface....
"This interface is implemented by the Visual Studio Tools for Office runtime. It is not intended to be implemented in your code. For more information, see Visual Studio Tools for Office Runtime Overview."
That's why you have to reference the application interface after initializing a new workbook.
Please mark this as answered if it resolved your question.

excel import using c#

i am working on excel import to grid view using DataTable in c#, but my problem is its working fine on my local system but its redirecting to login page on my online server and i have tried both Microsoft.Office.Interop.Excel & OLEdb connection. but the problem is same. please tell me what is the problem with these or any one have any other function to import Excel data in GridView.
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Have a look:
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
It is better not using MS Office interop in server cases which will bring a lot of performance and memory issues in the future. Recommend using some 3rd party library, for example: https://www.nuget.org/packages/Spread.Services/ to get what you wanted.

Parse Excel document for keywords using C#

I need to parse the excel document for certain keywords using C# and count the number of their occurrences. These keywords are required to be searched within a certain range, which is not fixed.
Please provide some help for this.
Thanks!
You may try something like this (i'm using Excel Interop here):
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
Excel.Workbook wk = app.Workbooks.Open(#"D:\testExcel.xlsx");
Excel.Worksheet sh = (Excel.Worksheet)wk.ActiveSheet;
Excel.Range rng = sh.get_Range("A1", "Z20");
Console.WriteLine(CountWord(rng, "a"));
wk.Close(false);
app.Quit();
Console.ReadLine();
}
private static int CountWord(Excel.Range rng, string word)
{
int i = 0;
Excel.Range rng1 = rng.Find(word);
if (rng1 != null)
i++;
else
return 0;
string address = rng1.Address;
Console.WriteLine(address);
while (true)
{
rng1 = rng.FindNext(rng1);
if (rng1 == null)
return i;
Console.WriteLine(rng1.Address);
if (rng1.Address == address)
return i;
else
i++;
}
}
}
}
You have to use Microsoft.Office.Interop.Excel in your C# code then the below source code will search in first row for the Excel sfilename is filename
int countOccurence = 0;
public bool SearchRows(string valTosearch)
{
Excel.Application xlApp = new Excel.Application();
xlApp.ScreenUpdating = false;
try
{
xlApp.DisplayAlerts = false;
vk_filename = SFileName;
//Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(SFileName);
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(
SFileName, vk_update_links, vk_read_only,
vk_format, vk_password,
vk_write_res_password,
vk_ignore_read_only_recommend, vk_origin,
vk_delimiter, vk_editable, vk_notify,
vk_converter, vk_add_to_mru,
vk_local, vk_corrupt_load);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
// loop trough cell range and excel rows below will search in 1st row
Excel.Worksheet worksheet = xlRange.Worksheet;
for (int iCount = 1; iCount <= colCount; iCount++)
{
string cellValue = "";
string fldValue = "";
Microsoft.Office.Interop.Excel.Range fldRange = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, iCount];
if (fldRange.Value2 != null)
{
fldValue = fldRange.Value2.ToString().Trim().ToLower();
}
else
{
fldValue = null;
}
Microsoft.Office.Interop.Excel.Range CellRange = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[2, iCount];
if (CellRange.Value2 != null)
{
cellValue = CellRange.Value2.ToString().Trim().ToLower();
if (cellvalue == valtosearch)
{
countOccurence +=1;
}
}
else
{
cellValue = null;
}
}
xlWorkbook.Close(vk_save_changes, vk_filename, vk_route_workbook);
//xlWorkbook.Save();
xlApp.Quit();
return true;
}
catch
{
xlApp.Quit();
return false;
}
}

Categories