I'm trying to retrieve the sum of a row from an excel document.
When googling this all of the solutions involved writing a =SUM(1:1) like formula into a cell and then writing the result to a variable.
Since I don't want to edit the excel file i was wondering if it's possible to retrieve the sum of a row range directly into a variable without the pit stop?
Thanks in Advance!
This will save the sum of the values of two cells into "myVariable"
Dim myWB As Workbook
Set myWB = ActiveWorkbook
Set ws = myWB.Sheets(1)
Dim myVariable As Variant
myVariable = ws.Cells(1,1).Value + ws.Cells(2,1).Value
If you are using xlsx files you can use this cool lib :
https://closedxml.codeplex.com/documentation
It uses DocumentFormat.OpenXml you can install closedXml and dependancies with this command :
Install-Package ClosedXML
Example to do a sum on the first row :
//open the excel file
var wb = new XLWorkbook("excel File path");
//get the first worksheel
var ws = wb.Worksheet(0);
var lineNumber = 0;
var startColumn = 0;
var endColumn = 10;
var cells = ws.Range(lineNumber, startColumn, lineNumber, endColumn).Cells().ToList();
var sum = cells.Sum(xlCell => (int) xlCell.Value);
Related
I am using NPOI library in order to read .xls and .xlsx files.
However I have this issue, the method GetRow() does not return null even when the row is empty.
Here is the code
int idx_row = 1;
IRow currentRow = sheet.GetRow(idx_row);
while (currentRow != null)
{
JObject jsonData = new JObject();
jsonData["a"] = sheet.GetRow(idx_row).GetCell(0).StringCellValue.Replace(" ", "");
// other similar code
jsonPlateData.Add(jsonData);
idx_row++;
currentRow = sheet.GetRow(idx_row);
}
Check the value of sheet.LastRowNum, it's possible that the row seems empty but excel considers it as filled. If so, open the excel file and delete the rows that are "empty".
I using EPplus for exporting excel.i have to give a combo box.Currently i have given the range manually.but i want this dropdown for entire column.Can any one tell how to do this
ExcelPackage excel = new ExcelPackage();
ExcelWorksheet P = excel.Workbook.Worksheets.Add("Pass");
var droplist = P.DataValidations.AddListValidation("C2:C50000");
droplist.Formula.Values.Add("a");
droplist.Formula.Values.Add("b");
The following line should work:
var droplist = P.DataValidations.AddListValidation("C:C");
EDIT:
Alternatively, you can set ExcelRange to MaxRows. You can then define the range then skipping the first or first n rows. Code below skips first row:
var range = ExcelRange.GetAddress(2, 3, ExcelPackage.MaxRows, 3);
var val = p.DataValidations.AddListValidation(excelRange);
Where GetAddress is:
public static string GetAddress(int FromRow, int FromColumn, int ToRow, int ToColumn)
ExcelCellBase has the extension method to get an address: GetAddress
ExcelPackage has a public const MaxRows (1048576)
Using Excel Interop, you can get the count of rows in use by a sheet like so:
_xlSheet.UsedRange.Rows
(where "_xlSheet" is an Excel.Worksheet).
What is the equivalent in Spreadsheet Light?
You can add a worksheet like so:
var sl = new SLDocument();
. . .
sl.AddWorksheet("SheetsToTheWind");
...but how can you then access that worksheet to interrogate it for its used row count?
After adding the worksheet it is active as well. That means that you can get the WorksheetStatistics from the method GetWorksheetStatistics. That statistics instance has a NumberOfRows property:
// NOTE: The information is only current at point of retrieval.
var stats = sl.GetWorksheetStatistics();
var rowcount = stats.NumberOfRows;
If you want to to know the rowcount of all sheets you can do:
foreach(var name in sl.GetSheetNames())
{
sl.SelectWorksheet(name);
var stats = sl.GetWorksheetStatistics();
var rowcount = stats.NumberOfRows;
Trace.WriteLine(String.Format("sheet '{0}' has {1} rows", name, rowcount));
}
Adding to rene's answer:
Since accessing the Statistics' NumberOfRows property does not automagically update (you must call GetWorksheetStatistics() each time to get the up-to-date stats), I found it handy to write this helper method:
private int GetCurrentNumberOfRows()
{
// This reference to "sl" assumes that you have declared "SLDocument sl;" and
// instantiated it ("sl = new SLDocument();"), perhaps in your class' constructor
var stats = sl.GetWorksheetStatistics();
return stats.NumberOfRows;
}
..and then call it as needed:
int lastRow = GetCurrentNumberOfRows();
I need to convert all the words conataing in a sheet to uppercase using NPOI in C#; I can't find method to do this.
Before applying uppercase : Cell[1;1]=stackoverflow
After applying uppercase : Cell[1;1]=STACKOVERFLOW
I don't think it is possible without looping through cells using NPOI.Probably it can be done using Interop to Excel since it is possible to select range in file and perform some actions on it (like in Excel), but NPOI doesn't offers such ability.
Howewer, you don't need to loop through all cells in sheet since there exists properties FirstRowNum and LastRowNum and they gives you range of rows actually containing data.
So your loop could look like (converting to uppercase all strings from the first worksheet of file):
var hssfwb;
using (var file = new FileStream(#"your_file.xls", FileMode.Open, FileAccess.Read))
{
hssfwb = new HSSFWorkbook(file);
file.Close();
}
var sheet = hssfwb.GetSheetAt(0);
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
{
var row = sheet.GetRow(i);
if (row != null)
{
foreach (ICell cell in row.Cells.Where(c => c.CellType == CellType.String))
cell.SetCellValue(cell.StringCellValue.ToUpper());
}
}
I have a template spreadsheet document that has two columns, Server Name and IP Address.
How can I populate the spreadsheet so that each dictionary key goes in its own cell in the Server column and the corresponding value goes in the cell next to it in the IP column?
I am using the EPPlus library but couldn't find anything on the topic.
Below is what I found and tried, but its for lists
using (ExcelPackage package = new ExcelPackage(_fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
for (int i = 0; i < listOfIPs.Count; i++)
{
worksheet.Cells[i + 2, 1].Value = listOfIPs[i];
}
package.Save();
}
I am not familiar with EPPlus, therefore I am not sure how you get the reference to the active sheet - you need to figure out this bit though once that's done pure C# with a bit of knowledge about VBA model and you can easily avoid any iterations to get contents of your dictionary to a spreadsheet:
// create a sample dictionary and fill it
Dictionary<string, string> myCol = new Dictionary<string, string>();
myCol.Add("server1", "ip1");
myCol.Add("server2", "ip2");
// grab a reference to the active Sheet
// this may vary depending on what framework you are using
Worksheet ws = Globals.ThisWorkbook.ActiveSheet as Worksheet;
// create a Range variable
Range myRange;
// Transpose the keys to column A
myRange = ws.get_Range("A1");
myRange.get_Resize(myCol.Keys.ToArray().Count(),1).Value =
ws.Parent.Parent.Transpose(myCol.Keys.AsEnumerable().ToArray());
// transpose the Values to column B
myRange = ws.get_Range("B1");
myRange.get_Resize(myCol.Values.ToArray().Count(), 1).Value =
ws.Parent.Parent.Transpose(myCol.Values.AsEnumerable().ToArray());
Debugging results as expected
With EPPlus I think you can do it like this (untested)
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium);
package.Save();
}
More details on VBA Collections iterations and printing to Sheet # vba4all.com
You can just access the keys of a dictionary and iterate over them just like you are iterating over the list.
var foo = new Dictionary<string, string>(); // populate your dictionary
foreach(var key in foo.Keys)
{
var value = foo[key];
// do stuff with 'key' and 'value', like put them into the excel doc
}