我试图通过选择所有单元格从excel表中删除重复项.所以我知道如何处理一个列.但我想用整张纸做.
这就是我尝试过的:
private void RemoveDuplicateRecords()
{
try
{
var ar = new int[0];
foreach (Excel.Worksheet worksheet in bookDest.Worksheets)
{
if (worksheet.AutoFilter != null)
worksheet.AutoFilterMode = false;
int n = worksheet.UsedRange.Columns.Count;
ar = new int[n];
for (int i = 0; i < n;)
{
ar[i] = ++i;
}
object cols = new object[] { ar }; //isn't working
Excel.Range range = worksheet.UsedRange;
range.Select();
range.Activate();
range.RemoveDuplicates(cols, Excel.XlYesNoGuess.xlYes);
//Also tried:
//range.RemoveDuplicates((object)ar, Excel.XlYesNoGuess.xlYes); //but no luck
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
我知道如果我有5列,我可以这样做:object cols = new object [] {1,2,3,4,5};
但我不想手动完成.我想动态添加列. Excel文件可以包含任何no.of列.对此有任何帮助表示赞赏.谢谢您的帮助.
最佳答案 我想这应该有效:
//To remove all the duplicate lines in the result file
private void RemoveDuplicateRecords()
{
try
{
foreach (Excel.Worksheet worksheet in bookDest.Worksheets)
{
if (worksheet.AutoFilter != null)
worksheet.AutoFilterMode = false;
long n = worksheet.UsedRange.Columns.Count;
Excel.Range range = worksheet.UsedRange;
range.Select();
range.Activate();
range.RemoveDuplicates(BuildColAry(n), Excel.XlYesNoGuess.xlYes);
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
dynamic BuildColAry(long n)
{
dynamic vMyArray = new dynamic[n];
int idx;
for (idx = 1; idx <= n; idx++)
{
vMyArray[idx - 1] = idx;
}
return vMyArray;
}