简体   繁体   English

将数据从* .csv复制到Excel

[英]Copying data from *.csv into excel

I have a csv file that is filled with outputs from a temperature sensor, it has date, temperature controller address, temp sensor 1 value, temp sensor 2 value, heat power, cool power and limit and alarm states, here is an example with spaces added for readability when opened in notepad: 我有一个csv文件,里面装有温度传感器的输出,它具有日期,温度控制器地址,温度传感器1的值,温度传感器2的值,热功率,冷功率以及极限和警报状态,这是一个带空格的示例在记事本中打开时增加了可读性:

2/10/2016 14:52:26.2, 1, 73.9039, 74.89208, 14.63515, 0, F, None, None, None,
2/10/2016 14:52:36.594, 1, 73.75067, 74.86765, 25.21247, 0, F, None, None, None,
2/10/2016 14:52:47.165, 1, 73.66284, 74.83871, 35.95927, 0, F, None, None, None,
2/10/2016 14:52:57.788, 1, 73.59991, 74.79031, 47.17537, 0, F, None, None, None,
2/10/2016 14:53:8.381, 1, 73.54018, 74.75883, 58.62064, 0, F, None, None, None,

however, if I open it in excel, i get this format: 但是,如果我在excel中打开它,则会得到以下格式:

52:26.2, 1, 73.9039, 74.89208, 14.63515, 0, F, None, None, None
52:36.6, 1, 73.75067, 74.86765, 25.21247, 0, F, None, None, None
52:47.2, 1, 73.66284, 74.83871, 35.95927, 0, F, None, None, None
52:57.8, 1, 73.59991, 74.79031, 47.17537, 0, F, None, None, None
53:08.4, 1, 73.54018, 74.75883, 58.62064, 0, F, None, None, None

I'm trying to use vba in excel to pull the data from this csv file or multiple csv files based on user selection through a file picker dialog into a workbook for graphing. 我试图在Excel中使用vba根据用户选择通过文件选择器对话框从此csv文件或多个csv文件中提取数据到工作簿中进行绘图。 The problem I'm running into is that the date and time column doesn't show up correctly. 我遇到的问题是日期和时间列未正确显示。 I think it has something to do with the formatting I'm using for the data, but I'm not sure. 我认为这与我用于数据的格式有关,但我不确定。 The format I use is 我使用的格式是

m/d/yyyy h:mm:ss.000

For some reason this is the data that shows up in the excel file: 由于某种原因,这是显示在excel文件中的数据:

1/0/1900 0:52:26.200, 1, 73.90390, 74.89208, 14.64, 0, F, None, None, None
1/0/1900 0:52:36.600, 1, 73.75067, 74.86765, 25.21, 0, F, None, None, None
1/0/1900 0:52:47.200, 1, 73.66284, 74.83871, 35.96, 0, F, None, None, None
1/0/1900 0:52:57.800, 1, 73.59991, 74.79031, 47.18, 0, F, None, None, None
1/0/1900 0:53:08.400, 1, 73.54018, 74.75883, 58.62, 0, F, None, None, None

I tried formatting the first column as a number with the format 我尝试将第一列格式化为带有格式的数字

0.0000000000

then moving the data, but the column is just blank then because I had to use a range data type to be able to change the format. 然后移动数据,但是该列只是空白,因为我必须使用范围数据类型才能更改格式。 Here is the code I use to show the file picker and move the data: 这是我用来显示文件选择器和移动数据的代码:

    Sub fileDialogStart()

    Dim fd As FileDialog
    Dim vrtSelectedItem As Variant

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
                ' Finds the last row in the current workbook
                With ThisWorkbook.Sheets(1)
                    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
                End With
                ' Imports the data from the selected file
                Call importData(vrtSelectedItem)
            Next vrtSelectedItem
        Else
        End If
    End With

    Set fd = Nothing
End Sub

Sub importData(ByVal filePath As String)

    Dim targetWorkbook As Workbook, sourceWorkbook As Workbook
    Dim finalRow As Integer
    'Dim targetData as Range

    Set sourceWorkbook = Workbooks.Open(filePath)

    With sourceWorkbook.Sheets(1)
        ' Finds the number of rows in the file selected from the file picker
        finalRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        ' Stores the first column
        targetData = .Range(.Cells(1, 1), .Cells(finalRow, 1))
    End With

    ' Sets the number format
    'targetData.NumberFormat = "0.0000000000"

    With ThisWorkbook.Sheets(1)
        ' Puts the new data into the current workbook after the last row of data
        ' in case there is already data in the workbook from a previous import
        .Range(.Cells(lastRow, 1), .Cells(lastRow + finalRow - 1, 1)) = targetData
    End With

    With sourceWorkbook.Sheets(1)
        ' Gets the rest of the data from the file selected
        sourceData = .Range(.Cells(1, 2), .Cells(finalRow, 10))
    End With

    With ThisWorkbook.Sheets(1)
        ' Puts the rest of the data into the current workbook
        .Range(.Cells(lastRow, 2), .Cells(lastRow + finalRow - 1, 10)) = sourceData
    End With

    sourceWorkbook.Save
    ThisWorkbook.Save
    sourceWorkbook.Close False
End Sub

The fileDialogStart() sub is called in the sub used to graph at the very beginning and I set the format of the entire first column back to m/d/yyy h:mm:ss.000 in there after the data is imported. fileDialogStart()在用于图形化的子fileDialogStart()中调用fileDialogStart()m/d/yyy h:mm:ss.000 ,在导入数据后,我将整个第一列的格式设置为m/d/yyy h:mm:ss.000 Maybe the problem has something to do with the fact that i'm opening the csv file as a workbook? 也许问题与我将csv文件作为工作簿打开的事实有关? I'm not sure. 我不确定。 Any help would be appreciated, thanks! 任何帮助,将不胜感激,谢谢!

The Workbooks.OpenText method allows you to specify the TextFileColumnDataTypes property of each field. Workbooks.OpenText方法允许您指定每个字段的TextFileColumnDataTypes属性 This equates to the Range.TextToColumns method . 等效Range.TextToColumns方法 Specifying an xlMDYFormat format for the first field is sufficient to bring the datetimes in correctly (including their fractions of seconds). 为第一个字段指定xlMDYFormat格式足以正确输入日期时间(包括其秒数)。

Sub openCSV()
    Dim fp As String, fn As String, wbCSV As Workbook

    fp = Environ("TMP")
    fn = "datetemp.csv"
    Debug.Print fp & Chr(92) & fn
    Workbooks.OpenText Filename:=fp & Chr(92) & fn, DataType:=xlDelimited, _
                       Tab:=False, Semicolon:=False, Space:=False, _
                       Other:=False, Comma:=True, FieldInfo:=Array(1, xlMDYFormat), _
                       Local:=True
    With ActiveWorkbook
        With Worksheets(1)
            With .Columns(1)
                .NumberFormat = "mm/dd/yyyy  hh:mm:ss.000"
                .AutoFit
            End With
        End With
    End With

End Sub

The Local:=True may not be desired depending upon your own regional settings. 根据您自己的区域设置,可能不需要Local:= True It worked fine for my EN-US defaults. 对于我的EN-US默认值,它工作正常。

Excel is doing some weird things; Excel正在做一些奇怪的事情; however when I run this: 但是,当我运行此:

Sub WTF()
   Dim FilesToOpen
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction
   Dim ary, bry, DQ As String
   DQ = Chr(34)

   FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")

   Close #1
   Open FilesToOpen For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      ary = Split(TextLine, ",")
      bry = Split(ary(0), " ")
         Cells(j, 1).Formula = "=datevalue(" & DQ & bry(0) & DQ & ")+timevalue(" & DQ & bry(1) & DQ & ")"
         Cells(j, 1).NumberFormat = "mm/dd/yyyy hh:mm:ss.000"
         For k = 2 To 10
            Cells(j, k) = ary(k - 1)
         Next k
      j = j + 1
   Loop

   Close #1
End Sub

On your posted data, I get: 在您发布的数据上,我得到:

在此处输入图片说明

What I cannot explain is why Excel does such a poor job of opening the file directly. 我无法解释的是为什么Excel直接打开文件的工作如此糟糕。

Perhaps some one else can explain this. 也许其他人可以解释这一点。

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

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