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".
Related
I am working of csv file with c#, I am able to return the number of rows and columns of the file, however I am still need to check if the there a new row is added to the file as well as if has empty cell or not.
any idea?
{
var contents = File.ReadAllText(item).Split('\n');
var csv = from line in contents
select line.Split(';').ToArray();
list.Add(new CSVFile
{
Colums = csv.FirstOrDefault().Count(),
Rows = contents.Length - 1,
Date = DateTime.Now,
Report = item.Split("\\").LastOrDefault(),
});
}```
I found a strange error with generating an Excel file using EPPlus library. The scenario is simple - I need to have many worksheets in a single excel file. But, when invoking the GetAsByteArray() method, I get the null reference exception
using (ExcelPackage xml = new ExcelPackage())
{
foreach (var mainValueItem in values)
{
using (ExcelWorksheet worksheet = xml.Workbook.Worksheets.Add($"sheet {mainValueItem.ID}"))
{
worksheet.Cells[1, 1].Value = "Date";
}
}
return ctr.File(xml.GetAsByteArray(), MediaTypeNames.Application.Octet);
}
I can see in both Worksheets, the Cells property is not loaded as you can see here:
so, how to create many worksheets ?
I've found an answer - we shouldn't use
using (ExcelWorksheet worksheet = xml.Workbook.Worksheets.Add($"sheet {mainValueItem.ID}"))
in that scenario. instead, just declare a variable
var worksheet = xml.Workbook.Worksheets.Add($"sheet {mainValueItem.ID}");
and now it works, I can see multiple tabs in the generated file.
Happy coding !
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);
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
}