我有这个问题,无论我尝试什么方法,我都无法在for循环的每次迭代中更新变量,以便我可以在循环的百分比中向用户显示当前状态。继承我的方法:
void startOperation()
{
Console.WriteLine("Beginning start operations..." + searchText);
Console.WriteLine("Opening Workbook: " + filePath);
// create excel-instance:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
// open the concrete file:
Workbook xlWorkbook = xlApp.Workbooks.Open(@filePath);
//MessageBox.Show(filePath);
// select worksheet. NOT zero-based!!:
_Worksheet xlWorksheet = xlWorkbook.Sheets[1];
//MessageBox.Show(Convert.ToString(xlWorksheet.Name));
Microsoft.Office.Interop.Excel.Range range;
int numRows = xlWorksheet.UsedRange.Rows.Count;
currRow = 1;
numRowsDeleted = 0;
nullCounter = 0;
decimal percentageComp;
//Parallel.For(1, numRows, new ParallelOptions { MaxDegreeOfParallelism = 1 }, i =>
for (int i = 1; i < numRows; i++)
{
percentageComp = currRow / numRows * 100;
Console.Clear();
Console.WriteLine("Number of Rows: " + numRows);
Console.WriteLine("Checking Row #: " + currRow);
Console.WriteLine("Number of Rows Deleted: " + numRowsDeleted);
Console.WriteLine("Percentage Complete: " + percentageComp);
if (i > 1)
{
i -= 1;
}
//Create Worksheet Range
range = (Microsoft.Office.Interop.Excel.Range)xlWorksheet.Cells[i, 2];
//MessageBox.Show(cellValue);
if (nullCounter == nullCount) //was 5, decreased to 3, then changed to nullCount variable
{
closeOperation(xlApp, xlWorkbook);
break;
}
if (Convert.ToString(range.Value) != null) //if (cellValue != null || cellValue != "")
{
cellValue = Convert.ToString(range.Value);
nullCounter = 0;
if (cellValue.Contains(searchText))
{
//MessageBox.Show("Found a row that needs deleting!");
//range.Rows[i].Delete(XlDeleteShiftDirection.xlShiftUp);
//Thread.Sleep(5);
xlWorksheet.Rows[i].Delete(XlDeleteShiftDirection.xlShiftUp);
//((Range)xlWorksheet.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
numRowsDeleted++;
//nullCounter = 0;
i--;
currRow++;
}
else
{
currRow++;
//percentageComp = currRow / numRows * 100;
//nullCounter = 0;
}
}
else
{
//MessageBox.Show("Null cell value");
nullCounter++;
}
i++;
}
//);
}
无论我尝试什么,我的控制台输出只显示0.我很困惑我可能在这里做错了所以任何帮助表示赞赏。谢谢你的时间!
答案 0 :(得分:1)
currRow
是一个整数,numRows
也是。 curRow
小于 numRows
。
整数除法的结果是整数。 40 / 100
不到一个。唯一小于1的整数值为零。对于任何整数x
和`y,其中x
小于y
,x / y
小于1 - 这将截断为零。
一旦你得到零,你可以将零乘以你喜欢的任何数字 - 它仍然为零。
所以不要使用整数除法。将它们投射到decimal
。
percentageComp = ((decimal)currRow / (decimal)numRows) * 100;
评论中的人发现了一堆其他的错误,看看那些也是如此。