簡體   English   中英

如何將VB.net與Excel工作表一起使用以對數據進行計數和排序

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

就像標題中所說的那樣,我一直在使用VB.NET在Excel上做各種事情,這有點新。 如果我有一個包含各種數據(包括員工和出售的物品)的Excel工作表,我如何選擇2列並對它們進行排序,以便計算每個人在“消息框”或“列表框”中出售的每件物品的數量?

例如,我正在尋找的輸出是這樣的

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...

我得到的最詳細的信息是統計每列中有多少工作人員,但我想更進一步,獲得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

任何指導,這將幫助我很多

答案上的延遲很小,但這是從Interop創建數據透視表的相關代碼(很抱歉,它是C#),然后使用該數據透視表來匯總結果。 這樣做很好,因為一旦完成了數據透視表,您就知道已對所有唯一條目進行了排序。 然后,您可以迭代數據透視表以獲取所需的結果。 在某些情況下,這比在.NET方面構建所有邏輯更容易,因為Excel非常擅長聚合數據。 缺點是您必須創建數據透視表。

這是完整的代碼,用於創建偽數據並將其匯總為盡可能通用的形式。

//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);
    }

}

生成的Workbook圖片的側面有數據透視表:

在此處輸入圖片說明

控制台輸出包括具有結果的行。 顯示的是最后幾行:

...
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