Click here to Skip to main content
6,306,412 members and growing! (21,628 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate

CSV to Excel XML Spreadsheet with VB.net

By Brasstax

Simple program to create Excel XML spreadsheets from CSV files. Utility with source.
VB, Windows, .NET, Visual Studio, Dev
Posted:22 Aug 2006
Views:30,369
Bookmarked:23 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
5 votes for this article.
Popularity: 2.64 Rating: 3.78 out of 5

1
1 vote, 20.0%
2
1 vote, 20.0%
3
1 vote, 20.0%
4
2 votes, 40.0%
5

Sample Image - csvtoexcelxml.jpg

Introduction

Have you ever been frustrated by the fact that you (or your users) can't simply double-click a .csv file that contains fields that have leading zeros without having them truncated by Excel during the "auto-import"?  An acquaintance of mine was in just such a situation and was crying out for help.

I created this simple little application that helps alleviate the pain. I thought I would post it here just in case someone else might find it useful.

Using the code

The code is very straightforward.  It uses an XML header and footer taken straight out of an Excel XML spreadsheet.  It opens the file the user has specified and then reads in each line from the file using a TextFieldParser. The application then creates rows for each line and writes them to the filesystem using a StreamWriter. Error checking has been removed from the source for clarity. However, "Try/Catch" statements should be added to handle possible errors that might be raised.


Public Class Form1

    Private sHeader As String = "<?xml version=""1.0""?><?mso-application progid=""Excel.Sheet""?>" + _
    "<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet"" xmlns:o=""urn:schemas-microsoft-com:office:office"" " + _
    "xmlns:x=""urn:schemas-microsoft-com:office:excel"" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"" " + _
    "xmlns:html=""http://www.w3.org/TR/REC-html40""><DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office"">" + _
    "</DocumentProperties> <ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel""> False" + _
    "False </ExcelWorkbook> <styles> <style ss:ID=""Default"" ss:Name=""Normal"">" + _
    ""Bottom""/>  <Font/>  <NumberFormat/>  </Style>" + _
    "<style ss:ID=""s21""> <NumberFormat ss:Format=""@""/> </Style> </Styles> <Worksheet ss:Name=""Sheet1"">" + _
    "<Table> <Column ss:StyleID=""s21""/>"

    Private sFooter As String = "</Table></Worksheet></Workbook>"

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        lblImportFileName.Text = ""
        lblExportFileName.Text = ""

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            lblImportFileName.Text = OpenFileDialog1.FileName
        End If

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            lblExportFileName.Text = SaveFileDialog1.FileName
        End If

    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        
        If lblImportFileName.Text = "" Or lblExportFileName.Text = "" Then
                MsgBox("Please select a file to import in CSV format and also a destination file location and name.")
                Windows.Forms.Cursor.Current = Cursors.Default                
                Exit Sub
        End If

        Dim MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(lblImportFileName.Text)
        MyReader.TextFieldType = FileIO.FieldType.Delimited
        MyReader.SetDelimiters(",")

        Dim file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(lblExportFileName.Text, False)

        file.Write(sHeader)
        Dim currentRow As String()
        While Not MyReader.EndOfData
            
           currentRow = MyReader.ReadFields()
           Dim currentField As String
           file.Write("<Row>")
           For Each currentField In currentRow
              file.Write("<Cell><Data ss:Type=""String"">" + currentField + "</Data></Cell>")
           Next
           file.Write("</Row>")
        End While
        file.Write(sFooter)
        file.Close()

        Windows.Forms.Cursor.Current = Cursors.Default
        MsgBox("Done")

    End Sub

End Class

Points of Interest

There is much more that can be done with an application like this.  This barely scratches the surface of what is possible with XML spreadsheets for Excel. I am looking forward to learning more.

History

8/23/2006 - Updated w/ source on the page
8/22/2006 - Initial application created

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Brasstax


Member

Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
  (Refresh) 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Aug 2006
Editor:
Copyright 2006 by Brasstax
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project