从Excel中插入两个原始列

时间:2019-01-30 10:37:10

标签: php mysql excel

嗨,我想从Excel文件中插入一些数据,但我不知道该怎么做 所以excel文件是这样的:

Empid| 1/01/2019|2/01/2019 | 3/01/2019
-------------------------------------------
1    |    A     |    B     |    A
2    |    B     |    A     |    B
3    |    B     |    C     |    C
4    |    A     |    A     |    A

而字母{A , B , C}代表班次类型,我想将表格从excel文件插入数据库,如下所示:

Empid | Date     | Shift
---------------------
 1    |1/01/2019 | A
 1    |2/01/2019 | B
 1    |3/01/2019 | A
 2    |1/01/2019 | B
 2    |2/01/2019 | A
 2    |3/01/2019 | B
 3    |1/01/2019 | B
 3    |2/01/2019 | C
 3    |3/01/2019 | C
 4    |1/01/2019 | A
 4    |2/01/2019 | A
 4    |3/01/2019 | A

非常感谢您。

1 个答案:

答案 0 :(得分:0)

此处已修改代码以适合您的目的。

Sub TransposeData()

    Const EmpidClm As String = "A"              ' change as applicable
    Const DateClm As String = "B"
    Const ShiftClm As String = "C"

    Dim Rng As Range
    Dim Arr As Variant, Pos As Variant
    Dim Rl As Long, Cl As Long
    Dim R As Long, C As Long
    Dim i As Long

    With ActiveSheet
        Cl = .UsedRange.Columns.Count - .UsedRange.Column + 1
        Rl = .Cells(.Rows.Count, Columns(EmpidClm).Column).End(xlUp).Row
        Set Rng = Range(.Cells(1, EmpidClm), .Cells(Rl, Cl))
    End With
    Arr = Rng.Value
    ReDim Pos(1 To (UBound(Arr) * UBound(Arr, 2)), 1 To 3)

    i = 1
    For C = 1 To 3
        Pos(i, C) = Array("Empid", "Date", "Shift")(C - 1)
    Next C

    For R = 2 To UBound(Arr)
        For C = 2 To UBound(Arr, 2)
            i = i + 1
            Pos(i, 1) = Arr(R, 1)
            Pos(i, 2) = Arr(1, C)
            Pos(i, 3) = Arr(R, C)
        Next C
    Next R

    R = Rl + 5                                  ' write 5 rows below existing data
    Set Rng = ActiveSheet.Cells(R, EmpidClm).Resize(i, 3)
    Rng.Value = Pos
End Sub