问题
My Excel file is not in tabular data. I am trying to read from an excel file. I have sections within my excel file that are tabular.
I need to loop through rows 3 to 20 which are tabular and read the data.
Here is party of my code:
string fileName = "C:\\Folder1\\Prev.xlsx";
var workbook = new XLWorkbook(fileName);
var ws1 = workbook.Worksheet(1);
How do I loop through rows 3 to 20 and read columns 3,4, 6, 7, 8? Also if a row is empty, how do I determine that so I can skip over it without reading that each column has a value for a given row.
回答1:
To access a row:
var row = ws1.Row(3);
To check if the row is empty:
bool empty = row.IsEmpty();
To access a cell (column) in a row:
var cell = row.Cell(3);
To get the value from a cell:
object value = cell.Value;
// or
string value = cell.GetValue<string>();
For more information see the documentation.
回答2:
I prefer using RowsUsed()
method to get a list of only those rows which are non-empty or has been edited by the user. This way I can avoid making checks for each row whether it is empty or not.
I'm not sure if it will fit the exact problem statement which you've described in your post but this code snippet can help you process 3rd to 20th row numbers out of all the non-empty rows as I've filtered out the empty rows before starting to process. Filtering the non-empty rows before I start processing can affect the row numbers you actually intend to process.
But I feel that RowsUsed()
method is very helpful in any general scenario when you are processing the rows of an excel sheet.
string fileName = "C:\\Folder1\\Prev.xlsx";
using (var excelWorkbook = new XLWorkbook(fileName))
{
var nonEmptyDataRows = excelWorkbook.Worksheet(1).RowsUsed();
foreach (var dataRow in nonEmptyDataRows)
{
//for row number check
if(dataRow.RowNumber() >=3 && dataRow.RowNumber() <= 20)
{
//to get column # 3's data
var cell = dataRow.Cell(3).Value;
}
}
}
回答3:
Here's my jam.
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row
foreach (var row in rows)
{
var rowNumber = row.RowNumber();
// Process the row
}
If you just use .RowsUsed()
, your range will contain a huge number of columns. Way more than are actually filled in!
So use .RangeUsed()
first to limit the range. This will help you process the file faster!
You can also use .Skip(1)
to skip over the column header row (if you have one).
来源:https://stackoverflow.com/questions/29655498/reading-from-excel-file-using-closedxml