将多列添加到 range.RemoveDuplicates
Add multiple columns to range.RemoveDuplicates
我正在尝试通过选择所有单元格从 excel sheet 中删除重复项。所以我知道如何在一个专栏上工作。但我想用整个 sheet.
这是我试过的:
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;
}
我正在尝试通过选择所有单元格从 excel sheet 中删除重复项。所以我知道如何在一个专栏上工作。但我想用整个 sheet.
这是我试过的:
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;
}