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.
Related
Which would be potentially a best way to enumerate or iterate or simply look for empty cells or cells with specific data structure in Excel, and later once you find it do some processing on it.
I tired Range, Value, Value2, etc but it takes fairly long time when Excel Sheet is considerably larger. I believe there must be some other efficient way.
It would be nice, if you can show some example snippet.
The answer is relativley simple: get the array in one batch from excel (search SO for a how to) - test the values of the erray for empty cells and then acess only the empty cells in excel.
It is somewhat cumbersome, but the fastes way because iterating each cell is vastly slower than simply getting all data in a batch.
To find blank cells, use the .SpecialCells method of a range object.
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.specialcells(v=office.11).aspx
The .specialCells method returns a range object of the matching criteria (i.e., xlCellTypeVisible, xlCellTypeBlanks, etc.). You can then iterate of this range to perform your formatting, etc.
Update I'm not a C# programmer, but I can show you how I would do this in VBA. Assuming interop exposes most/all of the same methods and functionality, you should hopefully be able to translate this for your purposes.
Sub ColorVisibles()
Dim rng As Range
Dim rngBlanks As Range
Dim blanksExist As Boolean
'define your range
Set rng = Range("A1:AA300")
'check to make sure there are blank cells in the range:
blanksExist = Application.WorksheetFunction.CountBlank(rng) > 0
If blanksExist Then
Set rngBlanks = rng.SpecialCells(xlCellTypeBlanks)
rngBlanks.Interior.Color = vbYellow
Else:
MsgBox "No blank cells exist in the specified range.", vbInformation
End If
End Sub
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.
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")
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.
I have to manipulate some Excel documents with C#. It's a batch process with no user interaction. It's going to parse data into a database, then output nice reports. The data is very dirty and cannot be ready using ADO. The data is nowhere near a nice table format.
Best is defined as the most stable(updates less likely to break)/ clear(succinct) code. Fast doesn't matter. If it runs in less than 8 hours I'm fine.
I have the logic to find the data worked out. All I need to make it run is basic cell navigation and getvalue type functions. Give me X cell value as string, if it matches Y value with levenshtein distance < 3, then give me Z cell value.
My question is, what is the best way to dig into the excel?
VSTO?
Excel Objects Library?
Third Option I'm not aware of?
VSTO is kind of a pain because of permissions and the fact that your dll becomes hooked to the document you're using. Assuming you're not actually changing the files, and ADO is definitely not an option, I would say that automation through the Excel COM interfaces is your best bet. It lets you program the way you normally would for any other application, and gives you just as many options for data extraction as VSTO.
The Office programs can be loaded as objects in .NET. The following is the coding stub that I used to load Excel into VB6. The code is essentially going to be the same regardless of which MS language you use.
Dim xlApp As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
On Error Resume Next
wb = xlApp.Workbooks.Open("c:\testdata.xls")
If Err.Number > 0 Then
If Err.Number = 1004 Then
MsgBox("File not found")
Else
MsgBox("Error " & Err.Number & " occurred.")
End If
Exit Sub
End If
ws = wb.Sheets("Sheet1")
Text1.Text = ws.Cells(1, 1).Value
wb = Nothing
ws = Nothing
xlApp = Nothing
Well try to see stack over flow question Convert Excel Range to ADO.NET DataSet or DataTable, etc