Controle a importação de CSV no Excel 2010 [duplicado]

0

Eu tenho um csv com valores como este:

"um valor muito longo, com uma vírgula", "387621937291732193"

O número, apesar de estar entre aspas, é transformado em um número no excel e aparece em notação científica. Como você evita que o excel presuma que tudo é um número? Por que o excel não mostra nenhuma opção ao abrir um arquivo CSV como o faz para arquivos .txt?

    
por Swaroop 09.04.2014 / 17:32

1 resposta

0

Você pode adicionar = ao início da string numérica:

"a very long value, with a comma",="387621937291732193"

Atualizar

Se você não puder alterar o CSV, terá duas opções. Você pode apenas definir a propriedade da coluna para exibir em formato numérico após o carregamento do CSV. Basta clicar com o botão direito na célula e selecionar Format Cell... . A partir daí, basta selecionar Number na lista. É o segundo item. Fechar e deve ficar bem.

Se você precisar que o arquivo para importar para o Excel já esteja correto, será necessário processar o arquivo por conta própria. Você pode fazer isso em qualquer linguagem de programação. Basta ler nos campos e enviá-los como quiser.

Aqui está um exemplo de vbscript:

' The columns begin at index 0, this array should include indexes for each column which should be treated literally.
' The script will add a = before these columns if it doesn't already exist.

' If you want you could add the ability to set this at the command line to make this more flexible.
literalColumns=Array(1)

'----------------------------------------------------------
' Nothing else should need to be changed.

IsOK=True
FileNotFound=False
CSVFileName=""
OutputFileName="output.csv" ' This is the default output file to use when none is given via the command line.

If WScript.Arguments.Count = 1 Or WScript.Arguments.Count = 2 Then
    CSVFileName = WScript.Arguments.Item(0)
    If WScript.Arguments.Count = 2 Then
        OutputFileName = WScript.Arguments.Item(1)
    End If
Else
    CSVFileName = InputBox("Enter a CSV file name to process:", "CSV Input File")
    If Len(CSVFileName) < 1 Then
        IsOK=False
        FileNotFound = True
    End If
End If

If IsOK Then
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(CSVFileName) Then
        ProcCSV CSVFileName, OutputFileName
    Else
        IsOK = False
        FileNotFound = True
    End If
End If

If IsOK = False Then
    msg="Usage: PrepCSV.vbs CSVFileName [OutputFileName]"
    If FileNotFound Then
        msg = msg & vbCrLf & vbCrLf &"File Not Found."
    End If
    Wscript.Echo msg
    Wscript.Quit
End If

Sub ProcCSV(InFileName, OutFileName)
    ReDim ToInsert(0)
    Set FS = CreateObject("Scripting.FileSystemObject")
    Set InFile = FS.OpenTextFile(InFileName, 1, False, -2)
    Set OutFile = objFSO.CreateTextFile(OutFileName)
    Set Regex = CreateObject("VBScript.RegExp")
    Regex.Pattern = """[^""]*""|[^,]*"
    Regex.Global = True
    Do While Not InFile.AtEndOfStream
        ReDim ToInsert(0)
        CSVLine = InFile.ReadLine
        For Each Match In Regex.Execute(CSVLine)
            If Match.Length > 0 Then
                ColDX = UBound(ToInsert)
                ReDim Preserve ToInsert(ColDX + 1)
                If InArray(ColDX, literalColumns) And Left(Match.Value, 1) <> "=" Then
                    ToInsert(ColDX) = "=" & Match.Value
                Else
                    ToInsert(ColDX) = Match.Value
                End If
            End If
        Next
        CSVLine = Join(ToInsert, ",")
        OutFile.Write Left(CSVLine, Len(CSVLine) - 1) & vbCrLf
    Loop
    InFile.Close
    OutFile.Close
End Sub

Function InArray(item, arr)
    For i=0 To UBound(arr)
        If arr(i) = item Then
            InArray=True
            Exit Function
        End If
    Next
    InArray=False
End Function

Para usar isso, basta salvar o texto acima em um arquivo chamado PrepCSV.vbs . Você pode então clicar nele e digitar o nome do arquivo para processar ou você pode chamá-lo a partir da linha de comando como:

PrepCSV.vbs inputfile.csv outputfile.csv
    
por 09.04.2014 / 17:46