XValue propery in excel interop - c#

I want to change the Xvalues in excel chart using Interop.
Following is what I am using. But it is not recognising Range.
Can anybody help me solve this?
chartPage.SetSourceData Range("A2:A4"), xlColumns
chartPage.SeriesCollection(1).XValues = Range("B2:B4")
It is not accepting Range, everywhere I am finding same answer.

Try to get the active worksheet and use range on it. Something like this:
_Worksheet ws = this.ActiveSheet
chartPage.SeriesCollection(1).XValues = ws.Range("B2:B4")

Related

Filter Range by specific Color Index/RGB using Worksheet.Range.Autofilter(Field,Criteria,Operator)

I am doing some automated excel manipulation using C#. I have been having a hard time figuring out how to autofilter based on a specific color.
There is very little documentation about this type of manipulation, however I have found some VB.net and VBA code for it. I cannot seem to convert the code to C# as "RGB" is not usable as it is in VB.net and VBA (See VB.net code below).
Since there has been no answers to this questions, I want to specify the code that needs to be looked at. In Autofilter(Field,Criteria,Operator), I need to know the C# Microsoft.Office.Interop.Excel criteria that would let me choose a color to filter.
Here is what my code looks like:
Excel.Worksheet xs1:
Excel.Range xRange1;
Excel.Range xRange2;
Excel.Range lastrow;
Excel.Range lastcol;
lastrow = xs1.Rows.End[Excel.XlDirection.xlDown];
lastcol = xs1.Columns.End[Excel.XlDirection.xlToRight];
xRange1 = xs1.Cells[2, 14];
xRange2 = xs1.Cells[lastrow.Row, 14];
Below selects the entire sheet and adds an autofilter(), setting it to filter for color. This works fine, but how do I pick the color I want it to filter for?
xs1.Range["A1", xs1.Cells[lastrow.Row, lastcol.Column]].
AutoFilter(14,Excel.XlColorIndex.xlColorIndexAutomatic,
Excel.XlAutoFilterOperator.xlFilterCellColor);
Here is an example of what the autofilter code would look like in VB.net. It looks very similar to this in an excel macro as well.
xs1.Range("A1", xs1.Cells(lastrow.Row, lastcol.Column)).
AutoFilter(Field:=14,Criteria1:=RGB(0,202,255),
Operator:=Excel.XlAutoFilterOperator.xlFilterCellColors)
So this is how you pick the color index for any poor souls that need to figure it out themselves. I could not find this anywhere on the internet.
xs1.Range["A1", xs1.Cells[lastrow.Row, lastcol.Column]].
AutoFilter(14, xlBook.Colors[33], Excel.XlAutoFilterOperator.xlFilterCellColor);
The important part is the "xlBook.Colors[33]". xlBook being the Workbook. 33 being the color index.
I don't have any reputation points, so I must submit an answer instead of a comment. Anyway, thank you, thank you, thank you. I have spent weeks looking for this answer and happened to search the right key words to find this post. I signed up just to upvote the answer!
My scenario is not exactly like yours, but similar enough that you led me to the solution. So, I will share what worked for me. I am trying to filter by color index using PowerShell. However, PowerShell does not allow the RGB values, as in the VB.net example above. Now, for my contribution to the answer. If you are doing this in PowerShell then it will need to look like this:
$xlFilterCellColor = 8
$xl = New-Object -comobject excel.application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open("\\path\to\file.xlsx")
$ws = $wb.worksheets.items(1)
$xlCellTypeLastCell = 11
$used = $ws.usedRange
$lastCell = $used.SpecialCells($xlCellTypeLastCell)
$range = $ws.range(A1:$lastCell)
$range.select | out-null
$range.autofilter(1,$wb.colors(6),$xlFilterCellColor)
The operator decimal values are listed here. In the code above, I am filtering yellow colored cells. Cell index colors and values can be found here.

Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y].Style?

I found some code which uses Style property of Microsoft.Office.Interop.Excel.Worksheet.Cells[x,y] but it is treated as an object in my Visual Studo code editor:
Workbook wb = new Application.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = wb.Sheets[1];
ws.Cells[x,y] is simply treated as an object so how can I use its Style property?
I'm using Microsoft Excel 15.0 Objects Library (goes with Microsoft Office 2013). Does that matter?
Could you please explain this to me? Thank you.
you have to cast the object as a Range.
The Range interface/object contains all the style and value information for the cell or range that you are specifying.
some examples:
((Excel.Range)ws.Cells[r, c]).NumberFormat = format;
((Excel.Range)ws.Cells[r, c]).Value2 = cellVal;
((Excel.Range)ws.Cells[r, c]).Interior.Color = ColorTranslator.ToOle(Color.Red);
((Excel.Range)ws.Cells[r, c]).Style.Name = "Normal"
etc etc and so on.
Have a link:
https://learn.microsoft.com/en-us/office/vba/api/Excel.Range.Style
You might also like to check out stackoverflow.com/questions/15366340/ which includes cell formatting while exporting to excel.

Get the formatting of a cell in an Excel 2010 template

Im generating an Excel 2010 report based on a template in code using Microsoft.Office.Interop.Excel;
I need to grab the formatting from a cell in the template and apply it on subsequent cells down the column. To simplify, I want my cells to be right justified. Maybe its faster to specify this explicitly in code but I would prefer if I could base formatting on the template and not hardcode a particular style.
I am using workSheet.get_Range("L2", Type.Missing).get_Resize(1, 1) to select the cell.
Any suggestion greatly appreciated.
I'm not sure where get_Range() comes into the picture. I usually just get a Range directly.
I think what you are after is something to this effect (filler code there so you can see the variable names):
Dim oExcel As Object
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim AlignType As Long
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("MySheet.xlsx")
oSheet = oBook.Worksheets(1)
AlignType = oSheet.Range("G1").HorizontalAlignment
oSheet.Range("G1:G" & oSheet.Range("G1").End(Excel.XlDirection.xlDown).Row).HorizontalAlignment = AlignType
Change the ranges to suit your own code.
Basically, read the value out (it's an enum, so you don't need to get the actual setting, just its number), and write it back into the other cells. You could probably do it all in one step, I separated it for clarity.

C# Opening csv string in Excel without saving the string

I have a string in csv format, that I wish to simply open in Excel, without first having to save the file.
Is this possible? I've had a look at Interop but I cannot find the specific method that I need.
Thanks.
If you convert your csv-string to a 2-dimensional array first, you can pass it to a range of cells.
Excel.Range oRange = oSheet.Range("A1",Missing.Value);
oRange.Resize(myArray.GetLength(0),myArray.GetLength(1));
oRange.Value = myArray;
This code is written out of my mind, so I hope It's ok, but I think you get the picture.
If you like to include a header in your excel-file, just start the range from A2 instaed of A1.
Yes, just copy the values over manually. You can find a sample here.
Adapting that sample to get a very short sample to get you started (please note, this sample is not complete and you need to read the complete sample to see how to do things properly):
Excel.Application oXL= new Excel.Application();
oXL.Visible = true;
Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
Excel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = [first value from csv];
But assuming that it's a range of values in the csv string, just do a String.Split on it and then use the array to populate a Range in the sheet, just check out the sample in the article for details.

setting Excel cell format from C# using late binding

I'm using late binding to launch Excel from C# and copy data into it (Type.GetTypeFromProgID("Excel.Application"), Activator.CreateInstance, InvokeMember, and all that). I have this working fine, but I can't figure out how to set the cell format, specifically to make a cell bold. anyone have any idea how to do this?
I'm not sure how to do it late binding, but if you created an Excel helper class, this is probably the easiest way do what you want (I also added in color and number formating):
using System;
using Excel = Microsoft.Office.Interop.Excel;
public class MyClass
{
public void FormatRange(Excel.Worksheet sheet)
{
Excel.Range range = sheet.Cells["1","A"];
range.Interior.ColorIndex = 15;//This sets it to gray
range.Font.Bold = true;//Sets the Bold
range.NumberFormat = "#";//Sets it to numeric
}
}
Cheers!
SpreadsheetGear for .NET will let you read, modify and write Excel workbooks without relying on Excel being installed. If you are calling very many APIs, it will also run much faster than using Excel via COM Interop. Here is an example which loads a workbook, sets a cell's font to bold and saves the workbook:
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(#"C:\tmp\MyWorkbook.xlsx");
workbook.Worksheets["Sheet1"].Cells["A1"].Font.Bold = true;
workbook.Save();
You can see a number of live samples here and download the free trial here.
Disclaimer: I own SpreadsheetGear LLC

Categories

Resources