I am using c# program to search a text in my excel sheet. i have excel sheet called "MASTER" and in that sheet, there are a lot of text in column B. I want to look for
text "apple" inside column B. here is my code:
Excel.Worksheet workSheet;
workSheet = (Excel.Worksheet)xlWorkBook.Worksheets["MASTER"];
string result;
string utterance = "apples";
range1 = workSheet.Columns["B:B"] as Excel.Range;
Excel.Range findRange
findRange = range1.Find(utterance);
result = (string) (range2.Cells[findRange1.Row, 2] as Excel.Range).Value2;
it can search through the column B for input utterance "apples". however, in that column, there are a lot of apples. "applepie", "applejam","apple", etc. and the result from above code is "applepie". I think it because it just find the text contain "apple". my question is how to make it find the exact string so the output will be "apple" from column B?
Range.Find has many other arguments (see documentation), especially LookAt, see demo below:
var app = new Excel.Application();
var workbook = app.Workbooks.Open("C:\\Path\\File.xlsx");
var sheet = workbook.Worksheets["MASTER"];
var range = (Excel.Range)sheet.Columns["B:B"];
var result = range.Find("apples", LookAt: Excel.XlLookAt.xlWhole);
var address = result.Address;//cell address
var value = result.Value2;//cell value
//close or do something else
You can use the method Split, to treat every word as an array element
range1 = workSheet.Columns["B:B"] as Excel.Range;
var words = range1.Split(' ');
foreach(var word in words)
{
if (word == utterance)
Console.WriteLine(word);
}
Related
How do I copy an Array to an Excel Range in C#?
Why does the below code not work?
If I assign it like this, then in each cell is the same value
Workbook workbook;
Worksheet worksheet;
List<double> flow = new List<double>();
workbook = excel.Workbooks.Open(filename);
worksheet = workbook.Worksheets.Add();
worksheet.Range[$"$A$1:$A{flow.count}"].Value = flow.ToArray();
Of course the list is filled with values. I have omitted this part here.
replace your last line with
Excel.Range range = sheetSource.UsedRange.Columns[columnIndx];
range.Value = application.WorksheetFunction.Transpose(flow.ToArray());
In my excel sheet I'm looking with my program for a key word like "Tescase". The parameter xlWhole dosen't find any range, but xlPart finds the key word. The problem with xlPart ist that it finds all the words in my excel sheet that contains the word "Testcase". But I would like to search only for the exact key word "Testcase".
Hear is my code:
var app = new Application();
var workbook = app.Workbooks.Open(pExcelFile);
var worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
Range range = worksheet.UsedRange;
Range findTestcaseColumn = range.Find(What: "Testcase", LookIn: XlFindLookIn.xlValues, LookAt: XlLookAt.xlWhole);
if (findTestcaseColumn != null ) {
// found
} else {
//not found
}
But xlPart finds the key word "Testcase":
Range findTestcaseColumn = range.Find(What: "Testcase", LookIn: XlFindLookIn.xlValues, LookAt: XlLookAt.xlPart);
Thanks for suggetions.
Same problem here from VBA inside Excel: I fill a cell with a text, then come back later with .find to add something in the cell next to it. With xlPart I find the cell, with xlWhole it fails. Very strange behaviour. Resetting the style of the search column back to standard is a solution, but that's insane of course. It should ignore the style or have an option to do so.
Please join me giving feedback to Microsoft.
https://learn.microsoft.com/nl-nl/office/vba/api/excel.range.find
Hi I have an excel file settings.xlsx. I want to read the data from this file and assign the variables used in my code with the data.
example
Column1 Column2
Row1 Data 500
Row2 Address 30
Row3 Value FPGA
I have Data,Address and Value as variables in my code.
Can someone assist me with a pseudocode of c# to open a file and read the contents from it as per my requirement?
I want to search "Data" word in the excel file and take the value next to the cell containing "Data" and assign it to the variable "Data". I know it is confusing but I really want the final data to look like something below.
Data=500 //Finally I want my variables to have the data as follows
Address=30
Value= FPGA
I tried opening a file in my code.But since I am new to c#,i am not able to understand what is going wrong in my code.
I am stuck at this point. Open function is giving an error. Kindly help me. I tried to open the excel file in my c# code. But somehow it is saying Open function overload method doesn't take one argument. How to open and read the file?
string Filepath = #Filename;
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var MyBook = excelapp.Workbooks.Open(Filepath);
It will be really helpful if somone gives a pseudocode for the same.
Hi,
I was able to open the file.
string Filepath = Path.Combine(Directory.GetCurrentDirectory(), Filename);
Excel.Application excelapp = new Excel.Application();
excelapp.Visible = true;
var Workbook = excelapp.Workbooks.Open(Filepath, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0,true,1, 0);
var xlWorkSheet = (Excel.Worksheet)Workbook.Worksheets.get_Item(2);
Excel.Range range = xlWorkSheet.UsedRange;
But when I try to store the cell value in my variable, it gives me an error. I somehow cannot use Cells.value. I tried using the following but not able to store the data. Can anybody help?
uint pbaudRate2 = Convert.ToUInt32(range.Value2.ToString());
If you can make a slight change in your excel file, there is a much easier way to read the data. You need to have Column names in the first row (any names will do e.g. "ColumnName", "ColumnValue"), and data in subsequent rows. Then you can use code like this:
string xlConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=yourfullfilepathandname.xlsx;Extended Properties='Excel 8.0;HDR=Yes;';";
var xlConn = new OleDbConnection(xlConnStr);
var da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", xlConn);
var xlDT = new DataTable();
da.Fill(xlDT);
You will now be able to access the values from the DataTable. In your case: xlDT.Rows[1][1] will hold the value of address (in this case 30). One thing to note: numbers in an Excel spreadsheet need to be retrieved as doubles and then cast if you want something else:
int myAddress = (int)(double)xlDT.Rows[1][1];
Here is a small demo how to read a range of Excel cells
// cf. http://support.microsoft.com/kb/302084/en-us
Excel.Application XL = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook WB = XL.Workbooks.Open(fileName, ReadOnly: true);
Excel._Worksheet WS = (Excel._Worksheet)WB.Sheets[sheetName];
Excel.Range R = WS.get_Range(GetAddress(row1, col1), GetAddress(row2, col2));
object[,] arr = (object[,])R.Value;
....
private string GetAddress(int rowNumber, int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName + rowNumber;
}
The cell values are copied to a 2D array of objects. Further processing depends on the value types.
Note that the transfer of an array is much faster than a nested loop of single cell copy operations.
How to create and set styles in Excel cells using C#?
I want to write something like "April 1st" with st as a superscript.
I would be using a string format not a date format.
I have tried http://msdn.microsoft.com/en-us/library/f1hh9fza.aspx but getting an The name 'Globals' does not exist in the current context error. I have added assembly Microsoft.Office.Interlop.Excel. Am I missing any other assembly?
Excel.Style style = Globals.ThisWorkbook.Styles.Add("NewStyle");
You actually don't want to change the font of the whole cell but you to change a portion of the text in the cell I take it.
You'll still need to retrieve the cell range and then adjust the characters within that range. here is an example where it's just adjusting the first cell. A1.
If you wanted to change the whole cell range to be superscript it would be done like this
currentRange.Font.Superscript = true;
void Main()
{
var app = new Application();
app.Visible = true;
var workbook = app.Workbooks.Add(1);
Sheets excelSheets = workbook.Worksheets;
string currentSheet = "Sheet1";
Worksheet worksheet1 = (Worksheet)excelSheets.get_Item(currentSheet);
worksheet1.Cells[1, 1] = "April 1st";
worksheet1.Cells[1, 2] = "April 2nd";
worksheet1.Cells[1, 3] = "April 3rd";
worksheet1.Cells[1, 4] = "April 4th";
// fill in the starting and ending range programmatically this is just an example.
string startRange = "A1";
string endRange = "A1";
Range currentRange = worksheet1.get_Range(startRange , endRange );
var text = currentRange.Text.ToString();
int length = text.Length;
int index = 0;
if(text.Contains("st"))
{
index =text.IndexOf("st");
}
//The other checks for "nd", "rd", "th" obviously check to see a # precedes these.
if(index > 0)
{
currentRange.get_Characters( index+1, 2).Font.Superscript = true;
}
}
As the MSDN article you've linked to states:
Applies to: The information in this topic applies to document-level
projects and application-level projects for Office 2013 and Office
2010. See Features Available by Office Application and Project Type.
To use Globals class you have to create Office project. For another reference you can check this question about creating Office add-in:
Globals.ThisAddin.Application can be only used in VSTO Add-In
I am trying to replace formulas on column D with their values.
eg. currently D1 = C1 / 2
If C1 = 10, I want D1 to be 5
I need to do this because I need to delete the column C.
I tried changing the format to Text like below but it doesn't seem to replace formulas with their values
Excel.Style style = workbook.Styles.Add("styleText", Missing.Value);
style.NumberFormat = "#";
Excel.Range range = (Excel.Range)sheet.get_Range("D1", Missing.Value);
range.Style = style;
Here's a macro in VBA that does what you need... It's VB code but I dont think woould be a problem to translate it in C#
Sub ValuesOnly()
Dim rRange As Range
On Error Resume Next
Set rRange = Application.InputBox(Prompt:="Select the formulas", Title:="VALUES ONLY", Type:=8)
If rRange Is Nothing Then Exit Sub
rRange = rRange.Value
End Sub
Another way to do it is to simply mimic the command Paste Special -> Values. I have just recorded a macro that does it (C5 in my sample is a cell that contains a function)
Sub Macro1()
Range("C5").Select
Selection.Copy
Range("D5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
How do you format a comment??
Here is the solution I got, thanks to Lorenzo
private static void ReplaceFormulasWithValues(ref Excel.Worksheet sheet, char column)
{
Excel.Range range = (Excel.Range)sheet.get_Range(column + "1", Missing.Value).EntireColumn;
range.Copy(Missing.Value);
range.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteValues,
Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
}
This is another way to do it (C1 contains a formula, the result is placed in D1)
static void Main( string[] args ) {
string fileName = #"D:\devprj\Temp\TempProject\bin\Debug\Cartel1.xlsx";
Application ac = new Application();
Workbook wb = ac.Workbooks.Open( fileName );
Worksheet ws = wb.Sheets[1];
Range rangeOrigin = ws.get_Range( "C1" );
Range rangeDestination = ws.get_Range( "D1" );
rangeDestination.Value = rangeOrigin.Value2;
wb.Save();
}
You can't just change the display style, because that doesn't change the content of the cell. When you're doing this manually in Excel you need to copy the column and then choose Paste Special -> Values to paste the values rather than the formulae. I imagine there's a programatic way to do the same operation.