我正在尝试通过选择所有单元格从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列。在这方面的任何帮助表示赞赏。感谢您的帮助。
答案 0 :(得分:1)
我想这应该起作用:
//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;
}