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;
}
}
Related
I want to append the column to the end of an existing excel file with Microsoft.Office.Interop.Excel in c#, I use Microsoft excel 2007, here is my code:
public void UpdateExcel_MSInterop(
string ExcelFile)
{
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook xlWorkbook = null;
try
{
//define ms excel application
xlApp = new Microsoft.Office.Interop.Excel.Application();
//
int Hwnd = xlApp.Hwnd;
xlApp.DisplayAlerts = false;
//
xlWorkbook = xlApp.Workbooks.Open(ExcelFile, Type.Missing, true);
int SheetIndex = 1;
foreach (Worksheet objSHT in xlWorkbook.Worksheets)
{
if (SheetIndex == 1)// ExcelSheetFullName.Substring(0, ExcelSheetFullName.Length - 1))
{
Range rng = objSHT.UsedRange;
int colCount = rng.Columns.Count;
int rowCount = rng.Rows.Count;
Range newRng = objSHT.get_Range(objSHT.Cells[1, 1], objSHT.Cells[1, colCount]).EntireColumn.Insert(Missing.Value,XlInsertShiftDirection.xlShiftToRight);
newRng.Cells[1, colCount + 1] = "State";
for (int r = 2; r <= rowCount; r++)
{
newRng.Cells[r, colCount + 1] = Products.Rows[r - 2]["state"].ToString();
}
break;
}
SheetIndex++;
}
xlWorkbook.Save();
if (xlWorkbook != null)
xlWorkbook.Close(SaveChanges:true);
if (xlApp != null)
xlApp.Quit();
}
catch (Exception ex)
{
if (xlWorkbook != null)
xlWorkbook.Close();
if (xlApp != null)
xlApp.Quit();
xlWorkbook = null;
xlApp = null;
MessageBox.Show(ex.Message + "\n" + ex.StackTrace.ToString());
throw ex;
}
}
I get error:
object dose not contain a definition for get_Range
How to fix this error, or if my approach is wrong how to append column to the end of an existing excel file,please give me example,Thanks for help.
I am trying to import an excel file to a datagrid in WPF. What I've found around the Internet won't rally do the trick.
I have a code that opens and reads excelfiles and outputs the data cells to a messagebox. I want to do so but to DataGrid instead. Here follows the code that needs to be changed:
private void ReadFromFile_Click(object sender, RoutedEventArgs e)
{
//Create COM Objects. Create a COM object for everything that is referenced
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\Temp\vitoshacademy.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
MessageBox.Show("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
To Import the Excel file into DataGrid using C# in WPF
Using Microsoft.Office.Interop.Excel;
private async void btnImport_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string path = System.IO.Path.GetFullPath(choofdlog.FileName);
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
DataSet ds = new DataSet();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(path);
foreach (Microsoft.Office.Interop.Excel.Worksheet ws in wb.Worksheets)
{
System.Data.DataTable td = new System.Data.DataTable();
td = await Task.Run(() => formofDataTable(ws));
ds.Tables.Add(td);//This will give the DataTable from Excel file in Dataset
}
Datagrid.ItemsSource = ds.Tables[0].DefaultView;
wb.Close();
}
}
public System.Data.DataTable formofDataTable(Microsoft.Office.Interop.Excel.Worksheet ws)
{
System.Data.DataTable dt = new System.Data.DataTable();
string worksheetName = ws.Name;
dt.TableName = worksheetName;
Microsoft.Office.Interop.Excel.Range xlRange = ws.UsedRange;
object[,] valueArray = (object[,])xlRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
for (int k = 1; k <= valueArray.GetLength(1); k++)
{
dt.Columns.Add((string)valueArray[1, k]); //add columns to the data table.
}
object[] singleDValue = new object[valueArray.GetLength(1)]; //value array first row contains column names. so loop starts from 2 instead of 1
for (int i = 2; i <= valueArray.GetLength(0); i++)
{
for (int j = 0; j < valueArray.GetLength(1); j++)
{
if (valueArray[i, j + 1] != null)
{
singleDValue[j] = valueArray[i, j + 1].ToString();
}
else
{
singleDValue[j] = valueArray[i, j + 1];
}
}
dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}
return dt;
}
var excelApp = new Excel.Application();
var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);
var excelSheets1 = excelWorkbook.Worksheets;
var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];
for (var i = 2; i <= 62; i++)
{
for (var j = 2; j <= 5; j++)
{
var iRow = _dtCode1.NewRow();
var cellValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i, j]).Value);
var codeValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i + 1, j]).Value);
iRow[0] = cellValue; iRow[1] = codeValue;
_dtCode1.Rows.Add(iRow);
}
i = i + 1;
}
this code above in
var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];
i wanna change Sheet1 by ID like the number of sheet in the woorkbook
the second thing is there any way to close the excel file after open it
var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);
To select a sheet using its index use:
Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetFocus.Activate();
To close the workbook use
excelWorkbook.Close();
To quit Excel app:
excelApp.Quit();
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.
In my Windows based application(C#)
i want to import excel sheet to show its data in DatatGridView
i dont want to use oledb
any Help
using Excel = Microsoft.Office.Interop.Excel;
You'll obviously need to add the reference to your project, and then it's plain simple :)
private void ProcessExcel(string filepath)
{
Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass();
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range range = worksheet.UsedRange;
System.Array myvalues = (System.Array)range.Cells.Value2;
int vertical = myvalues.GetLength(0);
int horizontal = myvalues.GetLength(1);
string[] headers = new string[horizontal];
string[] data = new string[horizontal];
DataTable ResultsHeader = New DataTable();
DataSet ds = New DataSet();
for (int x = 1; x <= vertical; x++)
{
Utils.inicializarArrays(datos);
for (int y = 1; y <= horizontal; y++)
{
if (x == 1)
{
headers[y - 1] = myvalues.GetValue(x, y).ToString();
}
else
{
string auxdata = "";
if (myvalues.GetValue(x, y) != null)
auxdata = myvalues.GetValue(x, y).ToString();
data[y - 1] = auxdata;
}
}
if(x == 1) //headers
{
for(int w = 0; w < horizontal; w++)
{
ResultsHeader.Columns.Add(New DataColumn(headers[w], GetType(string)));
}
ds.Tables.Add(ResultsHeader);
}
else
{
DataRow dataRow = ds.Tables[0].NewRow();
for(int w = 0; w < horizontal; w++)
{
dataRow(headers[w]) = data[w]
}
ds.Tables[0].Rows.Add(dataRow);
}
}
DataView myDataView = new DataView();
myDataView.Table = ds.Tables[0];
MydataGrid.CurrentPageIndex = 0;
MydataGrid.DataSource = myDataView;
MydataGrid.DataBind();
}
I'm late to the party, but I have something worthwhile to add! I tried Juan's code and it didn't compile out-of-the-box. I modified it a little bit after researching the internet for a few more hours and got it to do exactly what the original poster asked (as I needed to do the same thing). I had to piece code together from other sources, and unfortunately, I did not keep track of what bits and pieces I tried and changed so I can't comment much about it.
The following code works in Visual Studio 2008 with .NET 3.5. Also, the formatting is lost when the data is put into the array (for example, dates become doubles which require a conversion with DateTime.FromOADate() to change it back). The issue with that is you can't tell if a value is an actual double or a date from a coding viewpoint, but if you know ahead of time a column is going to be a date, then format it as you insert the data into the table.
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new 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
dataGridView1.DataSource = dt;
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();
}
}
Those codes above does not work.
That code works for me (.NET Framework 4.7.1)
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new DataTable();
// must start with index = 1
// get header information
try
{
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(Convert.ToString(myValues.GetValue(1, i))));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] rows = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
rows[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = rows;
dt.Rows.Add(row);
}
// assign table to default data grid view
dataGridView1.DataSource = dt;
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();
}
}