读取 Excel 文件并跳过空行但不跳过空列
Read Excel file and skip empty rows but not empty columns
我希望读取 Excel 文件并跳过空行。我的代码跳过了空单元格,但它也跳过了空列。如何跳过空行但保留空列?我正在使用 JXL Java.
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con = cell.getContents();
if (con != null && con.length() != 0) {
System.out.print(con);
System.out.print("|");
}
else {
continue;
}
}
}
试试这个:
for (int i = 0; i < sheet.getRows(); i++) {
boolean rowEmpty = true;
String currentRow = "";
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con=cell.getContents();
if(con !=null && con.length()!=0){
rowEmpty = false;
}
currentRow += con + "|";
}
if(!rowEmpty) {
System.out.println(currentRow);
}
}
您正在做的是:
- 遍历行
- 遍历列
- 仅在单元格为空时打印单元格,否则跳过它(你的 continue 语句什么都不做,因为它是循环中的最后一条指令,而 break 语句一旦到达空单元格就会停止读取该行)
它的作用是:
- 遍历行
- 遍历列
- 将单元格附加到行的字符串,如果它不是空的,则将 rowEmpty 设置为 false(因为它包含至少一个非空单元格)
- 仅当行不为空时打印行
对于 C#,这对我有用
private bool CheckIfEmptyRow(ISheet worksheet, int rowIndex)
{
var worksheetRow = worksheet.GetRow(rowIndex);
bool isRowEmpty = true;
for (var columnIndex = worksheetRow.FirstCellNum; columnIndex < worksheetRow.LastCellNum; columnIndex++)
{
ICell cell = worksheetRow.GetCell(columnIndex, MissingCellPolicy.RETURN_NULL_AND_BLANK);
if (!string.IsNullOrEmpty(cell.StringCellValue))
{
isRowEmpty = false;
break;
}
}
return isRowEmpty;
}
我希望读取 Excel 文件并跳过空行。我的代码跳过了空单元格,但它也跳过了空列。如何跳过空行但保留空列?我正在使用 JXL Java.
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con = cell.getContents();
if (con != null && con.length() != 0) {
System.out.print(con);
System.out.print("|");
}
else {
continue;
}
}
}
试试这个:
for (int i = 0; i < sheet.getRows(); i++) {
boolean rowEmpty = true;
String currentRow = "";
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con=cell.getContents();
if(con !=null && con.length()!=0){
rowEmpty = false;
}
currentRow += con + "|";
}
if(!rowEmpty) {
System.out.println(currentRow);
}
}
您正在做的是:
- 遍历行
- 遍历列
- 仅在单元格为空时打印单元格,否则跳过它(你的 continue 语句什么都不做,因为它是循环中的最后一条指令,而 break 语句一旦到达空单元格就会停止读取该行)
- 遍历列
它的作用是:
- 遍历行
- 遍历列
- 将单元格附加到行的字符串,如果它不是空的,则将 rowEmpty 设置为 false(因为它包含至少一个非空单元格)
- 仅当行不为空时打印行
- 遍历列
对于 C#,这对我有用
private bool CheckIfEmptyRow(ISheet worksheet, int rowIndex)
{
var worksheetRow = worksheet.GetRow(rowIndex);
bool isRowEmpty = true;
for (var columnIndex = worksheetRow.FirstCellNum; columnIndex < worksheetRow.LastCellNum; columnIndex++)
{
ICell cell = worksheetRow.GetCell(columnIndex, MissingCellPolicy.RETURN_NULL_AND_BLANK);
if (!string.IsNullOrEmpty(cell.StringCellValue))
{
isRowEmpty = false;
break;
}
}
return isRowEmpty;
}