Searching date string in file excel - c#

I'm working with an excel file and I'm trying to find the position(address) of the cells with date value like "16/02/2015" as content. In order to do this with windows Forms application I use a datetimepicker. My code is as following:
// Firstly I want a string like 16/02/2015 inserted in the datetimepicker
string date = DateTimePicker1.Value.ToString().Substring(0,10);
List<string> Testsdone = new List<string>();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(file_opened, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);
Excel.Range currentFind = null;
Excel.Range firstFind = null;
Excel.Range tests = xlWorkSheet.get_Range("K13", "K2295");
currentFind = tests.Find(date);
.....
I have exactly the same content "16/02/2015" written in my excel file, but the currectFind always shows null! I have no idea why the two "16/02/2015" are different. Anybody got an idea? thanks!

Well after some investigation I found that the problem is caused by the Find function
currentFind = tests.Find(date);
which for unknown reason failed to find the date. From another post
how to Search in excel file I got this method, that I changed this into:
currentFind = xlworkSheet.Cells.Find(date, Type.Missing, Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole, Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false,Type.Missing, Type.Missing);
And it works. But I still have no idea why the Excel.Range.Find fails and Excel.workersheet.Cells.Find works

Related

Saving Excel File as Read Only (Interop.Excel) C#

All,
I have the below code which opens a specified excel file deletes the first row and then saves it as a specified CSV.
However when it saves the CSV down it saves it in a read-only format. Can anyone advise how I would ensure the file is not saved down in read only format.
EDIT
I have tried;
To set the ReadOnly property to false.
I also am aware two instances of Excel may be opening which may cause the read only status from googling previous posts however including myApp.Quit()
I believe it would close all instances of excel.
public void DeleteRows(string OriginalFileName,String NewFileName)
{
Microsoft.Office.Interop.Excel.Application myApp;
Microsoft.Office.Interop.Excel.Workbook myWorkBook;
Microsoft.Office.Interop.Excel.Worksheet myWorkSheet;
Microsoft.Office.Interop.Excel.Range range;
myApp = new Microsoft.Office.Interop.Excel.Application();
myWorkBook = myApp.Workbooks.Open(OriginalFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
myWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)myWorkBook.Worksheets.get_Item(1);
range = (Microsoft.Office.Interop.Excel.Range)myWorkSheet.Application.Rows[1, Type.Missing];
range.Select();
range.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
myApp.DisplayAlerts = false;
myWorkSheet.SaveAs(NewFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
myWorkBook.Close(true);
myApp.Quit();
}
}
}
Try to set ReadOnlyRecommended as false while saving the excel file.
The solution was to change myWorkBook.Close(true); to myWorkBook.Close(false);

switch row/column of chart using c# excel interop

I'm currently working on a Programm which creates reports using Excel Interop. Therefore I intend to create a Line Chart as followed:
As one can see here I have a clear development of num and denom in relation to Milestones. When I select my values as chartRange manually in Excel I recieve this Diagramm. However, when do it programmatically (select exactly the same range) I get this:
Well, you can see the data selected. Excel (or something I don't know about) fails to recognize the Milestones row as axis. When I right click on the Diagramm --> select data --> Change rows/columns I get my right Chart.
Now does anybody know an order to switch those rows/columns or some way to define ranges for each of the axis?
I attached the relevant part of my code here:
Excel.Application myExcelApplication;
Excel.Workbook myExcelWorkbook;
object misValue = System.Reflection.Missing.Value;
myExcelApplication = null;
myExcelApplication = new Excel.Application();
myExcelApplication.Visible = true;
myExcelApplication.ScreenUpdating = true;
myExcelWorkbook = (Excel.Workbook)(myExcelApplication.Workbooks.Add(misValue));
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)myExcelApplication.Worksheets.Add();
newWorksheet.Name = requestedVehicles[m];
newWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
Excel.Range chartRange = myExcelApplication.get_Range("B2", endrange + 4);
Excel.ChartObjects xlCharts = (Excel.ChartObjects)newWorksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(100, 20, 500, 400);
Excel.Chart chartPage = myChart.Chart;
chartPage.HasTitle = true;
chartPage.ChartTitle.Text = "num/denom";
chartPage.SetSourceData(chartRange, Excel.XlRowCol.xlColumns);
chartPage.ChartType = Excel.XlChartType.xlXYScatterLines;
Thanks in advance,
Andy
I solved it myself due to this post I've stumbled across:
https://www.codeproject.com/questions/870177/csharp-excel-chart-x-axis-category-labels
The Problem was that the upper left cell of my defined range wasn't empty.. so Excel assumed it was supposed to be a data series.
hmmm, if the proposed solution does not work for all, this is how you can do it directly from the interop; use the method ChartWizard(), the parameter PlotBy does the trick.
This is how I use it:
wsChart.ChartWizard(Type.Missing, Type.Missing, Type.Missing, Excel.XlRowCol.xlRows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Here is the doc:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel._chart.chartwizard?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(Microsoft.Office.Interop.Excel._Chart.ChartWizard);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6);k(DevLang-csharp)%26rd%3Dtrue&view=excel-pia

Excel sheet read only and C#

I'm trying to edit an Excel Sheet through C# code but the Excel sheet is giving me an error saying read only
CS0200 Property or indexer 'Range.Text' cannot be assigned to -- it is read only
This is the code that is trying to access the sheet.
Code:
//Load workbook
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"S:\Utils\documents\ServerManager\serverlist.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlWorksheet.Range["D2"].Text = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
In the properties the Excel sheet is not read only and when I open it to edit it does not prompt me with the "This document is read only, want to enable editing." How can I go around this, Visual Studio won't let me compile because of it.
This is Excel in Office365.
You want to use .Value instead of .Text.
xlWorksheet.Range["D2"].Value = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
If you check the documentation you can see that Text is read-only.
Also, if you check the documentation you can see that Value is not read-only.
EDIT
You also might have to change your Open parameters to:
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Filename: "path/to/file", ReadOnly: false);

Excel worksheet get item

I have a problem with Excel worksheet. I am trying to create an Excel file with c#.
This code works and runs correctly on my computer but in other computers get an error at last line:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheetInvoice;
Excel.Worksheet xlWorkSheetInvoiceLine;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
at Microsoft.Office.Interop.Excel.Sheets.get_Item(Object Index)
I executed a sample application with similar code on a machine with Excel 2013 and it fails at the same line of code you mentioned. By default Excel 2013 application opens up with a single worksheet ("Sheet1") so you would have to modify the code accordingly
DISP_E_BADINDEX seems to suggest the number of worksheets is less on the other computers. Build in a check to see if the number of worksheets is less than 2 before using get_Item().
i have created new sheet and assigned xlWorkSheetInvoice and xlWorkSheetInvoiceLine to solve it.
var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
var xlNewSheet2= (Excel.Worksheet)xlSheets.Add(xlSheets[2], Type.Missing, Type.Missing, Type.Missing);
xlWorkSheetInvoice = xlNewSheet;
xlWorkSheetInvoiceLine = xlNewSheet2;
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);

How can I determine how many worksheets there are in an Excel workbook?

thanks in advance for your help. I want to loop through all worksheets in a workbook. Unfortunately, I don't know how many worksheets there are in a given workbook. Right now I use the following technique to enumerate through all worksheets:
Excel.Worksheet xlWorkSheet1;
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Worksheet xlWorkSheet2;
xlWorkSheet2 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
Excel.Worksheet xlWorkSheet3;
xlWorkSheet3 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
Is there a method that returns the number of worksheets in a workbook?
Use Excel.Workbook and then you can use the Workbook.Sheets.Count() in a for or while loop.
The Worksheets property has a collection of the worksheets .
foreach (Excel.Worksheet xlworksheet in xlworkbook.Worksheets)
{
//xlworksheet code here
}
Or, get the count value and use a for loop.
Googling this results in either this page, or several others where you have to use VBA or C# or start mucking about in the Name Manager in Excel.
Anyone looking for a quick and dirty solution:
Open the xlsx file with 7zip and navigate to xl\worksheets.
In there you should see all the sheets, and if you select those 7zip will count them for you.
Insert a module in the workbook you want to count the total sheets of,
Then type the below code and hit run
Public Sub CountWorksheets()
MsgBox "Total Sheets count:" & Application.Sheets.Count
End Sub
You'll get a relevant output like below
We can now use: int Workbook.Sheets.Count
I use this code:
//Create application.
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
//Opening excel book
Workbook ObjWorkBook = ObjExcel.Workbooks.Open(excelFileLocation, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Getting sheets count
int sheetsCount = ObjWorkBook.Worksheets.Count;
For this code to work, you need to install the package using NuGet - Microsoft.Office.Interop.Excel

Categories