如何在dotnet中使用ClosedXML库实现EPPlus迭代功能?

huangapple go评论61阅读模式
英文:

How to achieve the EPPlus Iteration functionality using ClosedXML library in dotnet?

问题

我有以下代码,它在Excel工作表上使用EPPlus库遍历范围,现在我想使用ClosedXML库实现相同功能:

 ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
 DataTable table = new DataTable();
 foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
 {
     table.Columns.Add(firstRowCell.Text);
 }

我尝试过的是:

 ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
 DataTable table = new DataTable();
 foreach (var firstRowCell in workSheet.Range(1,1,LastRowUsed().RowNumber(),LastColumnUsed().ColumnNumber()))
 {
     table.Columns.Add(firstRowCell.Value.ToString());
 }

但它抛出一个异常,因为foreach不能遍历IXLRange类型的变量,因为它没有GetEnumerator定义,所以如何解决这个问题?

英文:

I have the following code which iterates over a range in excel worksheet using EPPlus library, now I want to achieve the same functionality using ClosedXML Library:

 ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
 DataTable table = new DataTable();
 foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
 {
     table.Columns.Add(firstRowCell.Text);
 }

What I've tried:

 ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
 DataTable table = new DataTable();
 foreach (var firstRowCell in workSheet.Range(1,1,LastRowUsed().RowNumber(),LastColumnUsed().ColumnNumber()))
 {
     table.Columns.Add(firstRowCell.Value.ToString());
 }

But it throws an exception that foreach cannot iterate over IXLRange type variable as it doesn't have any GetEnumerator definition, so how to solve this?

答案1

得分: 1

使用Cells()属性来迭代范围内的单元格(与您的原始代码相比,您还应该替换LastRowUsed().RowNumber(),或者这是有意的吗?):

ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
DataTable table = new DataTable();
foreach (var firstRowCell in workSheet.Range(1, 1, 1, LastColumnUsed().ColumnNumber()).Cells())
{
    table.Columns.Add(firstRowCell.Value.ToString());
}
英文:

Use the Cells() property to iterate over the cells in the range (and compared to your original code, you should replace LastRowUsed().RowNumber() also, or was this deliberate?):

ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
DataTable table = new DataTable();
foreach (var firstRowCell in workSheet.Range(1,1,1,LastColumnUsed().ColumnNumber()).Cells())
{
    table.Columns.Add(firstRowCell.Value.ToString());
}

huangapple
  • 本文由 发表于 2023年4月4日 07:51:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定