开发者

Copying a file and saving it in another format

I am copying a file from sample.csv to new.csv. After I copied I need to open new.csv and save i开发者_Go百科t as new.xls with worksheet name "Newsheet". I copied successfully but couldn't move on to open it/save it.

Here is my code:

    Dim ioFile As New System.IO.StreamReader("C:\sample.csv")      
    Dim ioLine As String
    Dim ioLines As String      
    ioLine = ioFile.ReadLine     
    ioLines = "ID,Name,Number,Amount"
    ioLines &= vbCrLf & ioLine 
    While Not ioLine = ""         
        ioLine = ioFile.ReadLine         
        ioLines = ioLines & vbCrLf & ioLine      
    End While     
    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")     
    ioWriter.WriteLine(ioLines)     
    ioFile.Close()     
    ioWriter.Close()


If you need to import a csv into Exel and you can use excel you can use the folowing code with modifications of course. As you can see I just recorded a macro. However I have used macro recording to give me a stub of much more complicated office automation Tasks. As long as you have the excel library all you need to do is add a reference to it open the app and then pull the code you need from below.

Sub Macro1()
'
' Macro1 Macro
'

'
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;H:\My Documents\InCps.TXT" _
        , Destination:=Range("$A$1"))
        .Name = "InCps"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub


Converting from basic text to Excel requires a little more work than a file extension change.

I'd take a look at the NPOI library, which allows you to easily create Excel documents (as well as other types) and is open source. It is easy to use and you should be able to get a working solution done fast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜