ope*_*tza 2 c# excel excel-interop
您好我有一个问题为什么最后一行永远不会被读取?如果excel文件中只有一行或100行,则无关紧要.最后一行永远不会出现在列表中.我不知道为什么......
这是我的方法:
public List<string> getListData(bool skipFirstRow, int numberOfColumns, string filepath)
{
int startpoint = 1;
int cell = 1;
int row = 1;
List<string> stringList = new List<string>();
//Open Excel (Application)
var excelApplication = openExcelApplication();
//Open Excel File
Excel.Workbook excelWorkbook = excelApplication.Workbooks.Open(filepath);
//Get the Worksheets from the file
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
//Select the first Worksheet
Excel.Worksheet worksheet = (Excel.Worksheet)excelSheets.get_Item(1);
if (skipFirstRow == true)
{
startpoint = 2;
}
Excel.Range range = worksheet.get_Range("A" + Convert.ToString(startpoint), Missing.Value);
while ((range.Cells[startpoint, cell] as Excel.Range).Value2 != null)
{
for (int i = 1; i <= numberOfColumns + 1; i++)
{
string sValue = (range.Cells[row, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
row++;
}
closeExcelApplication(excelApplication);
var result =
stringList
.Select((item, index) => new { Item = item, Index = index })
.GroupBy(x => x.Index / numberOfColumns)
.Select(g => string.Join(";", g.Select(x => x.Item)))
.ToList();
return result;
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用调试器甚至谷歌.然后我尝试了最后使用的行东西,但没有工作.
Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = worksheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
Run Code Online (Sandbox Code Playgroud)
任何帮助或建议都会很棒,所以感谢您的时间和帮助.
你的算法很麻烦.
让我们看看当skipFirstRow为true并且Excel工作表有三行1,2和3时会发生什么.在while循环开始时,我们有以下情况:
startpoint = 2
row = 1
Run Code Online (Sandbox Code Playgroud)
在第一次迭代期间,while循环读取第1行的内容.迭代之后,我们遇到以下情况:
startpoint = 3
row = 2
Run Code Online (Sandbox Code Playgroud)
在第二次迭代期间,while循环读取第2行的内容.迭代之后,我们遇到以下情况:
startpoint = 4
row = 3
Run Code Online (Sandbox Code Playgroud)
由于range.Cells[startpoint, cell]是空的,您的代码在此处停止.已读取第1行和第2行,已忽略第3行.
正如您所看到的,您遇到问题的原因是您检查了行startpoint并读取了行row,当这两行不同时,您就会遇到问题.建议的解决方案:删除startpoint变量并row改为使用.
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |