英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论