Link to home
Create AccountLog in
Visual Basic.NET

Visual Basic.NET

--

Questions

--

Followers

Top Experts

Avatar of Kevin
KevinπŸ‡ΊπŸ‡Έ

Format not correct when exporting to a CSV file
Good Afternoon,

I am developing an application in VB.Net where when a button is pressed values from an Access 2010 table are exported to a CSV (Comma delimited) file.

The problem I am experiencing is that the values of the below columns are not being formatted correctly when they are exported to the CSV.

ChqNum - Does not display leading 0's
Amount - Not displaying 2 decimal places when whole number (Example: Displays 456 when should really display as 456.00)

When I look at the values of the dataset using a breakpoint, the values are fine (below):

User generated image
But when they are written to the CSV file they are no longer formatted.

User generated image
Is anyone able to advise how I can fix this?

Code is below:

Imports System.Data.OleDb
Imports System.IO
Imports System.Data
Imports Microsoft.Win32
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel

Public Class frmMain

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

        'Initialize the objects before use
        Dim dataAdapter As New OleDbDataAdapter
        Dim dataSet As New DataSet
        Dim command As New OleDbCommand
        Dim dtMain As New System.Data.DataTable()
        Dim conn As New OleDb.OleDbConnection

        'Assign connection string to connection object
        conn.ConnectionString = sConnString()
        command.Connection = conn
        command.CommandType = CommandType.Text

        'Run query
        command.CommandText = "SELECT Format(ChqNum, '000000') As ChqNum, Format(ChqDate, 'mm/dd/yyyy') As ChqDate, Format(Amount, 'Standard') As Amount, PayTo, Reference, DebitAcc, CreditAcc, Currency, PayeeBank, Unit, Format(Voided, 'mm/dd/yyyy') As Voided FROM tblJBRHist"
        dataAdapter.SelectCommand = command

        Try

            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")

            Dim oExcel As Excel.Application
            Dim oBook As Excel.Workbook
            Dim oSheet As Excel.Worksheet
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Add(Type.Missing)
            oSheet = oBook.Worksheets(1)

            Dim dc As System.Data.DataColumn
            Dim dr As System.Data.DataRow
            Dim colIndex As Integer = 0
            Dim rowIndex As Integer = 0

            'Fill data to datatable
            conn.Open()
            dataAdapter.Fill(dtMain)
            conn.Close()

            'Export the Columns to CSV file
            For Each dc In dtMain.Columns
                colIndex = colIndex + 1
                oSheet.Cells(1, colIndex) = dc.ColumnName
            Next

            'Export the rows to CSV file
            For Each dr In dtMain.Rows
                rowIndex = rowIndex + 1
                colIndex = 0
                For Each dc In dtMain.Columns
                    colIndex = colIndex + 1
                    oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
                Next
            Next

            'Set final path
            Dim fileName As String = "\ExpJBRHistory" + ".csv"
            Dim finalPath = sExportString() + fileName

            'Save file in final path
            oBook.SaveAs(finalPath, XlFileFormat.xlCSV, Type.Missing, _
            Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, _
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)

            'Release the objects
            ReleaseObject(oSheet)
            oBook.Close(False, Type.Missing, Type.Missing)
            ReleaseObject(oBook)
            oExcel.Quit()
            ReleaseObject(oExcel)
            
            MessageBox.Show("Export done successfully!")

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)

        End Try

    End Sub

    Private Sub ReleaseObject(ByVal o As Object)

        Try

            While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)

            End While

        Catch

        Finally

            o = Nothing

        End Try
   
   End Sub
   
End Class

Open in new window


Kind Regards,
N

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Francisco IgorFrancisco IgorπŸ‡¨πŸ‡¦

Opening a CSV file in excel leads to a auto-formatting texts that appears as numbers.
(CSV does not define the format only the values)
You can try to enclose all values between ""Β for each fields you need

Avatar of KevinKevinπŸ‡ΊπŸ‡Έ

ASKER

Thank you for your response fraigor.

However opening the file in notepad after exporting it again is giving the same result.

User generated image
What I don't understand is why the dataset would pull the correct format and not the export in to the file.

Avatar of Francisco IgorFrancisco IgorπŸ‡¨πŸ‡¦

Try to change the format of cell before setting the value




Se this example:
http://www.aspose.com/docs/display/cellsnet/Setting+Display+Formats+of+Numbers+and+Dates

From line 61 change to:

Dim style As Style = oSheet.Cells(rowIndex + 1, colIndex).GetStyle()
if dc.ColumnName = "ChqNum" Then
style.Number = 49
End If
 oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
...

Open in new window


When you post to excel it's setting to format "general" instead of "text" (style=49) for the column ChqNum.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of KevinKevinπŸ‡ΊπŸ‡Έ

ASKER

Fraigor,

Am getting the below error when I add the above code.

User generated image
I'm wondering something, do I need to obtain the "Apose.Cells" API to get this to work with the code you provided?

Kindly advise.

Regards,
N

Avatar of Francisco IgorFrancisco IgorπŸ‡¨πŸ‡¦

Try Changing

Dim style As Style = oSheet.Cells(rowIndex + 1, colIndex).GetStyle()
if dc.ColumnName = "ChqNum" Then
style.Number = 49
End If

Open in new window


to

if dc.ColumnName = "ChqNum" Then
  oSheet.Cells(rowIndex + 1, colIndex).CellFormat.FormatString = "#######"
End If

Open in new window



See https://documentation.devexpress.com/#WindowsForms/CustomDocument2141Β to select the best format you need

Avatar of KevinKevinπŸ‡ΊπŸ‡Έ

ASKER

Thanks Fraigor, but it looks as though you also have to purchase this one (DevExpress) to be able to use it.

Are you able to maybe provide an alternative method altogether to what I am using for exporting an access 2010 table to a CSV (comma delimited) file? Maybe my approach is not possible without purchasing something, which is not an option for me.

Kindly advise.

Regards,
N

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of Francisco IgorFrancisco IgorπŸ‡¨πŸ‡¦

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of KevinKevinπŸ‡ΊπŸ‡Έ

ASKER

Hi fraigor,

Thank you for your response.

I can't seem to get the first set of code to work with the "CellFormat..."

Keep getting the below warning when run:

User generated image
The reason I am assuming that something needs to be referenced with another tool or something is because intellesence does not have an item for "CellFormat" only the below are available.

User generated image
So i'm assuming this is why I get that out of range error, because there is no reference for it.

However, your alternative with using the streamwriter for the export works like a charm. So will go with that approach since that works. Also I noticed with my previous approach that the Excel process would hang for whatever reason each time the export completed. So will scrap my initial approach all together.

Thanks very much for your help.

Kind Regards,
N
Visual Basic.NET

Visual Basic.NET

--

Questions

--

Followers

Top Experts

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,