logo Spire.XLS 系列教程 我也要发布文档

在C#中删除Excel中的重复行


Spire.XLS for .NET 是一款专业的 .NET Excel 组件, 它可以用在各种.NET 框架中,包括 .NET Core、ASP.NET 和 Windows Forms 等相关的.NET 应用程序。

本文演示了如何使用Spire.XLS for .NET在C#和VB.NET中的Excel文件中删除重复的行。

免费下载Spire.XLS最新版


下面是输入的Excel文件的屏幕截图:

Excel .NET组件Spire.XLS教程: 在C#中删除Excel中的重复行

C#

using Spire.Xls;
using System.Linq;

namespace RemoveDuplicateRows
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("TEST.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Specify the range that you want to remove duplicate records from.
            var range = sheet.Range["A1:A" + sheet.LastRow];
            //Get the duplicated row numbers  
            var duplicatedRows = range.Rows
                   .GroupBy(x => x.Columns[0].DisplayedText)
                   .Where(x => x.Count() > 1)
                   .SelectMany(x => x.Skip(1))
                   .Select(x => x.Columns[0].Row)
                   .ToList();

            //Remove the duplicate rows & blank rows if any           
            for (int i = 0; i < duplicatedRows.Count; i++) { sheet.DeleteRow(duplicatedRows[i] - i); } //Save the result file workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013); } } }

VB.NET

Imports Spire.Xls
Imports System.Linq

Namespace RemoveDuplicateRows
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim workbook As Workbook = New Workbook()
            workbook.LoadFromFile("TEST.xlsx")
            Dim sheet As Worksheet = workbook.Worksheets(0)
            Dim range = sheet.Range("A1:A" & sheet.LastRow)
            Dim duplicatedRows = range.Rows.GroupBy(Function(x) x.Columns(0).DisplayedText).Where(Function(x) x.Count() > 1).SelectMany(Function(x) x.Skip(1)).[Select](Function(x) x.Columns(0).Row).ToList()

            For i As Integer = 0 To duplicatedRows.Count - 1
                sheet.DeleteRow(duplicatedRows(i) - i)
            Next

            workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013)
        End Sub
    End Class
End Namespace

效果图:

Excel .NET组件Spire.XLS教程: 在C#中删除Excel中的重复行

慧都是E-iceblue官方友好合作伙伴,如果您对spire.xls,可以联系在线客服了解具体授权价格和使用机制。