简体   繁体   English

如何将VB.net与Excel工作表一起使用以对数据进行计数和排序

[英]How to use VB.net with an Excel sheet to count and sort data

Just like the title says, I've been using VB.NET to do various things on Excel and am kinda new. 就像标题中所说的那样,我一直在使用VB.NET在Excel上做各种事情,这有点新。 If i have an Excel sheet with various data including staff and things sold, how can i select 2 Columns and sort them so it counts how many of each items were sold by each person into a Messagebox or Listbox? 如果我有一个包含各种数据(包括员工和出售的物品)的Excel工作表,我如何选择2列并对它们进行排序,以便计算每个人在“消息框”或“列表框”中出售的每件物品的数量?

for eg, the output i'm looking for is something like 例如,我正在寻找的输出是这样的

Staff   Sold       how many
NAME1 - PRODUCT1 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT2 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT3 - AMOUNTSOLDBYNAME1
NAME1 - PRODUCT4 - AMOUNTSOLDBYNAME1
NAME2 - PRODUCT1 - AMOUNTSOLDBYNAME2
NAME2 - PRODUCT2 - AMOUNTSOLDBYNAME2

and so on...

the furthest i've gotten is counting how many of each staff member there are in 1 column but i would like to go a step further on this and get 2 columns and count each product sold by each person but am unclear how to go about it. 我得到的最详细的信息是统计每列中有多少工作人员,但我想更进一步,获得2列,计算每个人出售的每种产品,但不清楚如何处理。

Private Sub getexcelfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim excelfile As New OpenFileDialog()
    excelfile.ShowDialog()
    If (excelfile.ShowDialog() = DialogResult.Cancel) Then
        Return
    Else
        Dim file As String = excelfile.FileName
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet

        xlApp = New Excel.Application
        xlWorkBook = xlApp.Workbooks.Open(file)
        xlWorkSheet = xlWorkBook.Worksheets("PSSalesFullConnectionReport")

        Dim col As String = "N"
        For row As Integer = 1 To xlWorkSheet.UsedRange.Rows.Count - 1
            Dim elemValue As String = xlWorkSheet.Range(col & row).Text
            ListBox1.Items.Add(elemValue)
        Next

        MessageBox.Show(ReturnDuplicateListBoxItems(ListBox1))

        ListBox1.Items.Clear()

    End If

End Sub

Public Shared Function ReturnDuplicateListBoxItems(ByVal lBox As System.Windows.Forms.ListBox) As String
    Dim strReturn As New System.Text.StringBuilder
    Dim lItems As New Dictionary(Of String, Integer)
    Dim intCount As Integer = 0
    Dim strCurrentItem As String = String.Empty

    Try
        For Each nItem As String In lBox.Items
            If Not (lItems.ContainsKey(nItem)) Then
                strCurrentItem = nItem
                For Each sItem As String In lBox.Items
                    If sItem.Equals(strCurrentItem) Then
                        intCount += 1
                    End If
                Next
                lItems.Add(nItem, intCount)
                intCount = 0
                strCurrentItem = String.Empty
            End If
        Next

        For i As Integer = 0 To lItems.Count - 1
            strReturn.AppendLine(lItems.Keys(i).ToString & " - " & lItems.Values(i).ToString)
        Next

    Catch ex As Exception
        Return strReturn.ToString
    End Try

    Return strReturn.ToString
End Function

any guidance on this would help me alot 任何指导,这将帮助我很多

Slight delay on the answer, but here is relevant code for creating a Pivot Table from Interop (sorry, it's C#) and then using that Pivot Table to summarize the results. 答案上的延迟很小,但这是从Interop创建数据透视表的相关代码(很抱歉,它是C#),然后使用该数据透视表来汇总结果。 This is nice because once the Pivot Table is done, you know that you have all the unique entries sorted. 这样做很好,因为一旦完成了数据透视表,您就知道已对所有唯一条目进行了排序。 You can then iterate the Pivot Table to get the results that you want. 然后,您可以迭代数据透视表以获取所需的结果。 For some cases, this may be easier than building out all the logic on the .NET side of things since Excel is so good at aggregating data. 在某些情况下,这比在.NET方面构建所有逻辑更容易,因为Excel非常擅长聚合数据。 The downside is you have to create the Pivot Table. 缺点是您必须创建数据透视表。

This is full code to create dummy data and summarize it to be as general as possible. 这是完整的代码,用于创建伪数据并将其汇总为尽可能通用的形式。

//up above is a namespace usage that defines:
//using Excel = Microsoft.Office.Interop.Excel;
private void button1_Click(object sender, EventArgs e)
{
    Excel.Application xl_app = new Excel.Application();

    Excel.Workbook wkbk = xl_app.Workbooks.Add();
    Excel.Worksheet sht = wkbk.Worksheets[1];

    xl_app.Visible = true;

    //create some dummy data... not using an array.. I know
    Random rnd = new Random();

    int rows = 100;
    for (int i = 0; i < rows; i++)
    {
        sht.Cells[2 + i, 1].Value = "NAME" + rnd.Next(5);
        sht.Cells[2 + i, 2].Value = "PROD" + rnd.Next(5);
        sht.Cells[2 + i, 3].Value =  rnd.Next(10);
    }

    sht.Cells[1, 1].Value = "STAFF";
    sht.Cells[1, 2].Value = "SOLD";
    sht.Cells[1, 3].Value = "HOW MANY";

    //create the pivot table
    Excel.PivotCache pc = wkbk.PivotCaches().Add(
        Excel.XlPivotTableSourceType.xlDatabase, 
        sht.get_Range("A1").CurrentRegion);

    Excel.PivotTable pt = sht.PivotTables().Add(pc, sht.get_Range("F1"));

    pt.PivotFields("STAFF").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
    pt.PivotFields("SOLD").Orientation = Excel.XlPivotFieldOrientation.xlRowField;

    pt.AddDataField(pt.PivotFields("HOW MANY"), Type.Missing, Excel.XlConsolidationFunction.xlSum);
    //formatting here ensures it is a table with no extra values

    foreach (Excel.PivotField pf in pt.PivotFields())
    {
        pf.Subtotals[1] = false;
    }

    pt.ColumnGrand = false;
    pt.RowGrand = false;

    pt.RowAxisLayout(Excel.XlLayoutRowType.xlTabularRow);
    pt.RepeatAllLabels(Excel.XlPivotFieldRepeatLabels.xlRepeatLabels);

    //now we need to go through the Pivot Table to get data

    Excel.Range rng_start = sht.get_Range("F3");

    foreach (Excel.Range rng_cell in 
        sht.get_Range(
            rng_start, 
            rng_start.get_End(Excel.XlDirection.xlDown)))
    {
        Console.WriteLine("{0} - {1} - {2}",
            rng_cell.Value,
            rng_cell.get_Offset(0, 1).Value,
            rng_cell.get_Offset(0, 2).Value);
    }

}

Picture of the resulting Workbook has the Pivot Table over the on the side: 生成的Workbook图片的侧面有数据透视表:

在此处输入图片说明

Console output includes rows that have the results. 控制台输出包括具有结果的行。 Shown are the last couple lines: 显示的是最后几行:

...
NAME4 - PROD0 - 7
NAME4 - PROD1 - 11
NAME4 - PROD2 - 10
NAME4 - PROD3 - 17
NAME4 - PROD4 - 23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM