C# Opening csv string in Excel without saving the string - c#

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.

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.

XValue propery in excel interop

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")

C# read multiple Excel files [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is it possible to make an application that reads multiple excel files from a folder and extracts some information from them?
Yes it is, and here is how using Interop. The first thing you need to do is add the Excel Interop library to your project. You can do this by creating a new Visual Studio solution, right clicking on References, selecting Add Reference and then selecting Microsoft.Office.Interop.Excel from the .NET tab.
Then you need to add a using statement for Excel, and one for InteropServices (as we are interoping with a COM object):
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
Then, inside a method, you need to create an Application object:
Excel.Application application = new Excel.Application();
Next, create a Workbook object for each workbook you want to read from, like so:
Excel.Workbook workbookOne;
Excel.Workbook workbookTwo;
Excel.Workbook workbookThree;
Now use the Application object to open each workbook, and load each one into its respective Workbook object:
workbookOne = application.Workbooks.Open(#"C:\workbookOneLocation.xlsx");
workbookTwo = application.Workbooks.Open(#"C:\workbookTwoLocation.xlsx");
workbookThree = application.Workbooks.Open(#"C:\workbookThreeLocation.xlsx");
Now you need to decide what information you want to extract. Once you have done this determine which worksheet in the workbook it is on,and then figure out the number by simply looking at the tabs and counting. In the below example, Sheet2 is number 1, Sheet1 is number 2 and Sheet3 is number 3:
Create a variable for each piece of information you need like so (any value type variables will need to be nullable):
string firstPieceOfInformationINeed;
string[] secondPieceOfInformationINeed;
double? thirdPieceOfInformationINeed;
Let's say that the first piece of information we need is a string in Cell A1 on sheet one inside workbook one, the second piece is Cells B2 - B4 on worksheet two inside workbook two, and the third piece is a number on cell C5 on worksheet three inside workbook three. We would do this:
string firstPieceOfInformationINeed;
string[] secondPieceOfInformationINeed;
double? thirdPieceOfInformationINeed;
Excel.Worksheet worksheet;
Excel.Range range;
worksheet = workbookOne.Sheets[1];
range = worksheet.Cells["1", "1"];
firstPieceOfInformationINeed = range.Value as string;
worksheet = workbookTwo.Sheets[2];
range = worksheet.Range["B2", "B4"];
secondPieceOfInformationINeed = range.Value as string[];
worksheet = workbookThree.Sheets[3];
range = worksheet.Cells["3", "5"];
thirdPieceOfInformationINeed = range.Value as double?;
Then we close the workbook, using a boolean value to indicate whether or not we want to save changes:
workbookOne.Close(true);
workbookTwo.Close(false);
workbookThree.Close(true);
Now quit the application:
application.Quit();
And release the COM object:
Marshal.ReleaseComObject(application);
Now you are done with Excel, and have all of the different pieces of information you need stored as C# variables, and you can do with these what you wish.
Yes it is, and if you want to to that without Excel Interop you can use ClosedXML altough it works with excell 2007 + .
Try to use NPOI (http://npoi.codeplex.com/) or NetOffice (http://netoffice.codeplex.com/) library

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.

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