Finding the number of cells in a row that has data - c#

So I'm having a problem finding the number of rows in an excel document that has data in it. Here's what I have so far:
for (int i = 2; i <= b; i++)
{
if (!(worksheet.get_Range("A" + i, misValue).Formula == null))
{
a.Add(worksheet.get_Range("A" + i, misValue).Formula);
}
}
At the moment I'm just crudely shuffling through a large number of lines, questioning whether it's null or not, then adding the contents to a list. There has to be an easier way that google has yet to show me. Thanks for the help in advanced

I might not be understanding your question properly, but I'm guessing you're trying to find all the cells in column A that have a value in them and I'm assuming you're using Excel Interop in C#...
For that, you can use the Range.SpecialCells method.
So, for example, to get cells with constant values or formulas use:
worksheet.Range("A:A").SpecialCells(
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)
That will return a range you can loop through and add to your list, a....
See the documentation here
Hope this helps...

Related

how to add strings in text file to datagridview?

I have a text file that has values on each line and each value is separated by a comma.I want to add the first line of data in the first row of datagrid view and each value in first line separated with comma to be added in different columns of that row and second line of data in second row
I didn't know the actual code so I roughly tried this code:
string FilePath = Application.StartupPath + "\\Items.txt";
string[] Records = File.ReadAllLines(FilePath);
for (int i = 0; i < Records.Length; i++)
{
//listView1.Items.Add(Records[i],Records[i+1],Records[i+2]);
DGMenu.Rows.Add(Records[i]);
}
Records.Split(",") should give you what you need if I understood your question correctly.
You need to split each row with ',' and add that into DGMenu rows
for (int i = 0; i < Records.Length; i++)
{
DGMenu.Rows.Add(i.Split(','));
}
I understand that the answers so far have answered the OP's question as it was asked. However, I feel someone should point out that this isn't the most robust way to achieve the goal.
There appears to be an assumption that there will only be 3 entries per line. Maybe this is guaranteed, maybe it isn't? It's unclear from the question.
I'm assuming that somewhere in the example columns have been set up either in design time or in code...? Again it's unclear but I'm fairly certain you can't add rows in this way until columns exist. Please correct me if I'm wrong.
A better way (depending on whether or not this is product code or just some test app) is to do as Chris suggests and use some kind of parsing mechanism that provides a collection of instances of a type that can be data bound to the grid.
It looks like some of the info in the text file is a currency? Proper parsing and data binding would allow this information to be displayed as currency...
I could be barking up the wrong tree but I felt it should be mentioned.

Filling and manipulating matrices using MathNet.Numerics

I'm working on a code where I need to represent a small number of matrices (around 10) and do some operations with them (like get the inverse, transposed, etc). One of my co-workers recommended using the Math.Net Iridium library. The referred page said the project was Discontinued and merged with MathNeh.Numerics, found here.
I manage to install the package successfully. But now, I'm struggling to use the operations properly.
To sum up, what I am asking is: how to put data into matrices and manipulate them using MathNet.Numerics? For instance, how can I add values to a specific row x column y in a given matrix m1. Does it allow us to access a specific index?
One more thing to note, the matrices will always have the same number of columns and rows, but this number is known in run-time only.
I've tried to google for tutorials, found this one, but I didn't get what I needed to know. Any help is appreciated.
--
PS: the method I was using so far was creating Nested Lists to represent each matrix, and using for loops to populate it. I believe I would have a hard time when the time to transpose/invert/multiply would come.
The answer is in the documentation linked in the question itself. http://numerics.mathdotnet.com/Matrix.html#Manipulating-Matrices-and-Vectors
The given example is:
var m = Matrix<double>.Build.Dense(3,4,(i,j) => 10*i + j);
m[0,0]; // 0 (row 0, column 0)
m[2,0]; // 20 (row 2, column 0)
m[0,2]; // 2 (row 0, column 2)
m[0,2] = -1.0;
m[0,2]; // -1

Spreadsheetgear set data flags for specific column?

I am attempting to do this:
IWorksheet worksheet = Factory.GetWorkbook().Worksheets[0];
IRange range = worksheet.Cells["A1"];
range.CopyFromDataTable(dataTable, SetDataFlags.None);
worksheet.Cells.Columns.AutoFit();
return worksheet;
This works great normally, however I've run into an issue. I have one column that has a really long number, possibly with zeroes in the front and I need it to be entered and displayed as text. If I do a lookup of that particular cell like:
var cell = range["U34"].Value;
The data has already been turned into scientific notation so no amount of formatting afterwards fixes it. I tried SetDataFlags.AllText and that works great, except it breaks the rest of the worksheet because all of the numbers are stored as text, which is unacceptable.
I'm at a loss of how to fix this.
Solution:
Since I'm just looking to change one column, if it's present and a lot of the columns are dynamic I went with the "preformatting" route. Find the column index from the datatable:
int ColumnIndex = -1;
for (int x = 0; x < dataTable.Columns.Count; x++)
{
if (dataTable.Columns[x].ColumnName.Equals("Whatever"))
{
ColumnIndex = x;
}
}
worksheet.Cells[0, ColumnIndex, 0, ColumnIndex].EntireColumn.NumberFormat = "#";
Then perform the CopyFromDataTable, with Flags set to None and everything is perfect!
The IRange.CopyFromDataTable(...) method can be passed in a SetDataFlags.InsertCells enum option, which allows you to pre-format your destination range so that the inserted DataTable data picks up the formatting you specify. This formatting includes a cell's IRange.NumberFormat, which can be set to "#" and specifies that input to that cell should be treated as Text.
So, if you know what columns will have these unusually-large numbers that trigger scientific notation, another option would be to pre-format your worksheet's destination range with IRange.NumberFormat = "#" and will preserve your values for these columns as-is.
Please see the documentation for the IRange.CopyFromDataTable(...) method, as it provides important information on what range needs this "pre-formatting." Also, assuming you've installed SpreadsheetGear on your machine, check out the Reporting > DataSet to Workbook example in the SpreadsheetGear Explorer Solutions for C#/VB (found in the "SpreadsheetGear" folder under the Start Menu) for a live demo of this SetDataFlags.InsertCells option.

Edit Range NumberFormat in existing document

I can't change column format in an existing Excel document (xlsx). Columns content are numbers actually but shown as text and therefore green triangle appear telling that cells shown as text.
So I open this document in C# app and do the following thing:
sheet_.Range[sheet_.Cells[1, 2], sheet_.Cells[rowNum, 2]].EntireColumn.NumberFormat = "0";
But it doesn't change column to appear content as numbers (they remain aligned by left side)
I know this is an old post, but I've been dealing with the same problem. I receive .xlsx files that already have green triangles denoting "Number as Text" errors. I couldn't find a way to programmatically run the Excel error-checking command "Convert to Number" that you can do by clicking in Excel, and changing the NumberFormat on cells with these errors didn't work for me, but I was able to "refresh" the cell format by using the TextToColumns method.
int lastCol = sheet.UsedRange.Columns.Count;
if(lastCol > 1)
{
for (int i = 1; i <= lastCol; i++)
{
sheet.Columns[i].TextToColumns(Type.Missing, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierNone);
}
And from there you can change the NumberFormat. I happened to have long integers that were getting put into scientific notation, so I used this to make them regular integers again:
sheet.Cells.NumberFormat = "#";
(PS, if anyone finds a definitive guide on the symbols to use for customized NumberFormats, I'm still trying to find one!)
Try to access to cell value over get_Range method! for example and for what number format you want, lets say that you have in your excel cell this number : 1546,65
sheet_.get_Range("P10", "Q10").NumberFormat = "0"; // returns 1546
sheet_.get_Range("P10", "Q10").NumberFormat = "0,00"; // returns 1546,65
sheet_.get_Range("P10", "Q10").NumberFormat = "#.##0,00"; // returns 1.546,65
And you can play with these number formats!
Hope it helps you
I didn't find ideal solution to this issue and ended with the following:
sheet_.get_Range("A1", "A100").NumberFormat = "0";
for(int i = 1; i <= 100; i++)
{
sheet_.Cells[1, i].Value = sheet_.Cells[1, i].Value;
}
I know this is a old post but I stumbled over this and have a solution for this. Have you tried to not assign any NumberFormat? by default excel decides based on the cell content so you wouldnt get green triangle if you have numbers which are stored as text. If you want read values based on data type then refer this post
http://www.codeproject.com/Articles/335589/Export-Multiple-Datasets-to-Multiple-Excel-sheets
For me using the Style and the NumberFormatLocal solved the problem:
sheet_.get_Range("A1", "A100").Style.NumberFormatLocal = "0";

How to get revisions from Excel or PowerPoint Files in C# using Interop?

Am working on an application that needs to count words from documents and revisions.
as you can see here, I have already resolved this for Word Documents (well, as much it can be resolved) but now i find myself wondering how to get that data from Excel or PowerPoint documents.
The MSDN Documentation didn't help so far - i will keep looking but if anyone knows the answer i would appreciate a little help.
EDIT: So taking the information provided by #Andrew (Thanks go to him) i got this code for the Excel part:
foreach (Excel._Worksheet s in ExcelBook.Sheets)
{
if (s.UsedRange.Value2 != null)
{
for (int i = 1; i <= s.UsedRange.Value2.GetLength(0); i++)
{
for (int j = 1; j <= s.UsedRange.Value2.GetLength(1); j++)
{
string content = s.UsedRange.Value2[i, j];
MessageBox.Show(i + " - " + j + " - " + content);
}
}
}
}
Now i can use that to count words in all cells in the Sheet, however that still doesn't help with revisions - anyone has an idea on how to follow up on this?
It appears from the code example that you linked to that Word's OM gives you access to its revision tracking feature. Handy.
PowerPoint has no revision tracking whatever, so there's nothing for you to work with unless as Andrew has suggested, you extract and store the text from a presentation at one point, then later do the same and compare the two. Getting at the text, most of it anyhow, isn't all that difficult. Comparing two sets of text looking for revisions could be quite complex.
There are some VBA macros for extracting regular text on slides here (disclaimer: my site):
http://www.pptfaq.com/FAQ00274.htm
These are simple-minded and won't deal with text in grouped shapes, tables, charts and so on, but they'll get you started.
You should try this.
It helped me few months ago. It is a very nice tutorial on CodeProjects.

Categories