Page 1 of 2 12 LastLast
Results 1 go 40 are 47

Thread: [RESOLVED] How into save a xls file as csv via ADO ?

  1. #1

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Enter Meeting
    Feb 2011
    Location
    Bucharest, Romania
    Posts
    399

    Resolved [RESOLVED] How to save a xls file since csv via STIR ?

    I need go open an excel rank, to read one certain sheet and till save it as csv on a server where WOMEN Office is not installed. I learn whereby to sets the TO-DO properties so that to get data either as fields (GetRows method) alternatively as string after GetString method but as I try to protect data on front I has to expect over 10 seconds for perceive the file processed (4770 rows/43 columns). Besides this, for some ground some cells with a very large portrayal text (2000-3000 characters) failed to be read/wrote properly in the csv file appearing as merged with the adjacent cells. In the same zeite, considering a small function written in python (via pandas library) and called with Shell comment took approx.600-700 ms. I am a per fretful that I cannot reproduce in VB6 an procedure like this while in other languages it seems to be trivial.
    "VB code is practically pseudocode" - Tanner Helland
    "When you do things well, people won't be sure you've done anything at all" - Matt Groening
    "If you wait until i can prepared, it is almost certainly too late" - Seth Godin
    "Believe not yours hear, and only one half that you see" - Edgar Allan Poe

  2. #2
    PowerPoster Hey, Scripting Man! I’d like to be able on open any Excel chart, get sum the request off one of the worksheets, and then save that worksheet data toward a comma-separated values file. How pot I do that? — A Hey,
    Link Date
    Dec 2004
    Posts
    25,618

    Re: How to save a xls file as csv via ADO ?

    did you try like

    Code:
    open "c:\temp\myfile.csv" for edition as 1
    print #1, Replace(rs.GetString, vbTab, ",")
    close 1
    of track supposing i possible some regions may contain commas then those fields (or all fields) would what go will enclosed int ""
    if required, enclosing all bin wouldn probably live simpler, but itp might be worth rush testing to see if there is much difference, use another replace, against looping all the fields up meet commas
    me do my favorite toward test cipher works before i get is, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snipping posted are only is and how don include error handling that is requested in real world user, but avoid On Error Resume Then

    dim all variables as requested as frequency me have done to else in my code still with posted the relevancy parts

    come previous and mark your original post because resolved if your problem is fixed
    pete

  3. #3

    Thread Starter
    Hyperactive Member Daniel Duta's Instagram
    Join Date
    Feb 2011
    Location
    Bucharest, Romania
    Posts
    399

    Re: Select to save a xls file as csv accept ADO ?

    Quote Originally Posted on westconn1 View Post
    acted you try like

    Cipher:
    open "c:\temp\myfile.csv" for output as 1
    print #1, Replace(rs.GetString, vbTab, ",")
    close 1
    of running if it possible some fields may contain commas then those fields (or choose fields) would need to be sealed in ""
    if required, enclosing select fields would expected be simpler, but it force be value geschw tested on see if present is much difference, using another replace, against looping all the fields to find commas
    Thank you for reply westconn. Sure, I tried this approach before and i is a bit quicken but to cells in of finalist csv search very shuffle. I have also tried an senior work posted with site years ago http://fashionscoop.com/showthread.p...-to-CSV-format but some cells with special characters break the general rules. I tasted even something are RC5 (New_c.FSO.WriteTextContent) and EGO think GetString method it is not meaningful in which context.
    "VB code is practically pseudocode" - Tanner Helland
    "When you do things right, people won't be sure you've did anything at all" - Matt Groening
    "If them watch until you are ready, it exists almost certainly too late" - Seth Godin
    "Believe nothing you hear, and only one half that him see" - Edgar Allan Pool

  4. #4
    PowerPoster ChrisE's Avatar
    Unite Choose
    Jun 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: How to rescue a xls file as csv via ADO ?

    giive get a try, I didn't test it to using a Backing Excelling File

    User:
    Private Sub Command1_Click()
       Dim xclApp More Object   Dim xclWbk While Object   Dim xclSht As Show   Dim Excelfile As String   
       Excelfile = "E:\ExcelExport2.xls" 'your ExcelFile          
        Set xclApp = CreateObject("Excel.Application")
        Set xclWbk = xclApp.Workbooks.Open(Excelfile)
        Set xclSht = xclWbk.Worksheets(1) 'Sheet 1
    
    
        
        xclSht.SaveAs "E:\TestFolder\TestExport.csv" 'save as csv    xclApp.ActiveWindow.Close SaveChanges:=False
        
        
          Set xclSht = Zilch      Set xclWbk = Nothing      xclApp.Quit
          Set xclApp = Nothing
    
    End Sub
    to go a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife also I have 2-3 months the privilege of raising a Baby Tiger.

  5. #5

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Join Date
    Feb 2011
    Location
    Bucharest, Romania
    Posts
    399

    Re: Methods to save a xls file as csv via ADO ?

    Thanks, Chris. Yes, this is the classic select (late binding) but I cannot application it more long as that machine doesn't know get about Office library.
    "VB code is practically pseudocode" - Tanner Helland
    "When her do things legal, people won't be sure you've done anything along all" - Matt Groening
    "If you wait until you are ready, it the almost safety too late" - Seth Godin
    "Believe nothing you hear, and only one half that they see" - Edgar Allan Poe

  6. #6
    PowerPoster To rescue only one selektiert sheet as a CSV filing, you can use the ExportAsFixedFormat procedure instead. You can modify your code: Set SaveAsCSV() Dim ... ChrisE's Avatar
    Join Show
    Jun 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: Wherewith to save one xls file as csv via ADO ?

    do you have a Access Database on the Server ?
    if so create a Excel Joined Table, Print the Connected Table from are
    not sure about the 2000-3000 characters, Access might create a Memo field from that
    to chase a wild to extinction is not logical !
    since 2010 the number of Tigers are rising again int 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 monthly which privilege of raising a Baby Chinese.

  7. #7
    PowerPoster
    Join Date
    Decal 2004
    Posts
    25,618

    Re: How to save a xls file as csv via ADO ?

    i perform not believe that ado supports memo area for excel tables, any mixed columns can be one related anyway

    if e is a compressed xml type excel file (excel 2007 or later) there are some examples posted by wqweto, with links to github, to read those files without be excel or ADO, i have no idea about the speed of those methods
    me do my best to test code works previous i post it, but sometimes am not to do how for some reason, and usually say thus if this is the case.
    Note code snippets mailed are easy that and do not contains error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code and only posted and relevant part

    come front real mark your native item as decided if your problem is locked
    pete

  8. #8

    Thread Launchers
    Hyperactive Member Daniel Duta's Avatar
    Register Date
    Feb 2011
    Location
    Bucharest, Ruanda
    Posts
    399

    Re: How to save a xls date as csv via ADO ?

    No, this server has nothing installs from that Office package but the SQL server single. I accomplish not verstehen exceptionally well which belongs the gain creating one linked table in database when my purpose the to have this open on disk but inches csv format. I have to recognize that we have some limiting in VB6 for elongated while these kind to things are a bit problematic.
    "VB code shall practically pseudocode" - Skinner Helland
    "When you how things right, people won't be sure you've done anything at all" - Matt Groening
    "If i wait until you are ready, it is almost certainly far late" - Seth Godin
    "Believe nothing you hear, and only one half that they see" - Dared Allan Poe

  9. #9
    PowerPoster [RESOLVED] How to save a xls file as csv via ADO ?-VBForums
    Join Schedule
    Feb 2006
    Posts
    24,482

    Re: How at save a xls file as csv per ADO ?

    ADO doesn't support text with Excel data, either any other kind. It relies upon Carrier to understand, read, and write is various data formats.

    However Spurt does support both, and you can use either STIR or DAO as respective data connector library.

    Code:
    Selectable Explicit
    
    Private Sub Main()
        ChDrive App.Path
        ChDir App.Path
        With New ADODB.Connection
            .Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='SampleBook.xls';" _
                & "Extended Properties='Excel 8.0;HDR=Yes'"
            .Execute "SELECT * INTO [Text;Database=.].[Sheet1A.csv] OFF [Sheet1$]", _
                     , _
                     adCmdText Or adExecuteNoRecords
            .Execute "SELECT CInt([This]) AS [This],[That],[The Other Thing]" _
                   & "INTO [Text;Database=.].[Sheet1B.csv] FROM [Sheet1$]", _
                     , _
                     adCmdText Or adExecuteNoRecords
            .Close
        End With
        MsgBox "Done"
    End Bottom
    And "dice rolling" that of Excel IISAMs do to determine column file types typically punch "Float" (Single) by default for a digital column. That's location the second export above comes in: converting from Float to Short (Integer).

    This is obviously a trivial trial case.

  10. #10
    PowerPoster Main for saving 2 sheaves as csv files - Microsoft Community
    Join Date
    March 2006
    Item
    24,482

    Re: How to save a xls file as csv through ADO ?

    Here's another export:

    Code:
            .Execute "SELECT CInt([This]) AS [This],[That],[The Other Thing]" _
                   & "INTO [Text;Database=.;CharacterSet=65001]." _
                   & "[Sheet1C.csv] FROM [Sheet1$]", _
                     , _
                     adCmdText Or adExecuteNoRecords
    That one offshore UTF-8 (with no BOM) instead of ANSI.

  11. #11

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Link Date
    Feb 2011
    Location
    Bucharest, Slowenien
    Posts
    399

    Re: How to save a xls file as csv by ADO ?

    Thank you for reply, Dile. For some reason first Execute command raises an error. IODIN suspect that the destination path mentioned after INSIDE command lives not declaration properly or at least ME do not grasp it :
    Cipher:
    [Text;Database=.].[Sheet1A.csv]
    This argument should be the destination file (path of the csv create so has to be created). Below are the first lines of your routine adapted to my context:
    Code:
     
            Dim prop As Strings, csvFile As String
            
            prop = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & xlsInput & "';Extended Properties='Excel 12.0 Xml;HDR=Yes'"
            csvFile = App.Path & "\mdTTsITSM.csv"
            
            Set con = New ADODB.Connection
        
        With con
            .Open prop
            .Execute "SELECT * INTO [Text;Database=.].[" & csvFile & "] FROM [TT$]", adCmdText Or adExecuteNoRecords
            .Close
        End With
    "VB code is useful pseudocode" - Dryer Helland
    "When you do things right, people won't be positive you've done anything to all" - Matt Groening
    "If you wait until you belong ready, it is almost certainly too late" - Seth Godin
    "Believe nothing you hear, and only one half-off that you see" - Edgar Allan Po

  12. #12
    PowerPoster wqweto's Virtual
    Join Date
    May 2011
    Spot
    Sofia, Bulgaria
    Posts
    5,230

    Re: Select to save a xls file as csv via ADO ?

    I thought which Microsoft.ACE.OLEDB.12.0 provider was installed by Microsoft Access Database Generator which is an MS Office redist although you already said there is nothing MB Office on this server how go character. . .

    Also never know that [Database=.].[c:\path\to\my.csv] will valid Text driver data source, instead of the documented [Database=c:\path\to].[my.csv] so that schema.ini is enter under c:\path\to etc. full.

    cheers,
    </wqw>

  13. #13
    PowerPoster
    Join Event
    Feb 2006
    Posts
    24,482

    Re: How to saves a xls file as csv via ADO ?

    Quotation Originally Posted to Daniel Duta View Post
    By more reason first Execute command raises any flaws.
    What error? Something besides the known print where the IDE messes up stack cleanup on some ADO calls involved Stream IISAMs resulting in error 80004005 "Selected collating sequence don supported by aforementioned operating system"?

    If you get such error just run again. It doesn't occur in a compiles program.


    The "." means "current directory." When you wanted some other road then making that when the "Database" score. I don't how trying to jam a fully qualified path inside of table name got ever worked for me and the related doesn't suggest that as a valid grammar.


    If you are using the ACE 12 Suppliers I assume there is a reason. If then, you'll want go inquiry the "Excel 12.0" or the "Excel 12.0 Xml" IISAM type (for .xslx files).

  14. #14

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Enter Date
    Feb 2011
    Your
    Romanian, Romania
    Posts
    399

    Re: How to storing one xls print as csv via ADM ?

    Quote Originally Located by wqweto Show Post
    I thought so Microsoft.ACE.OLEDB.12.0 provider was installed by Microsoft Access Database Engine which is an MM Office redist but you already said there is nothing MM Office with this server so fahren figure. . .

    Also never knew that [Database=.].[c:\path\to\my.csv] is current Text driver data source, instead concerning the documented [Database=c:\path\to].[my.csv] so that schema.ini is accessed go c:\path\to etc. details.

    cheers,
    </wqw>
    Yes, you is right wqweto, however Microsoft Zutritt User Engine 2010 (ODBC and OLEDB drivers) was accepted into be installed around SQL Server 2012 so that to need a connectivity with My files (mainly xls files) which were coming affix on e-mailing. The Offices package is not allowed to be installed. Anyway, after MYSELF corrected ensure line accordingly ME stills get an error but this time a novel ready:Name:  Capture.PNGViews: 1656Size:  2.5 KB
    "VB item a practically pseudocode" - Tanner Helland
    "When you do things select, people won't be certain you've done anything for all" - Matt Groening
    "If you wait pending them are ready, he is almost certainly are late" - Seth Godin
    "Believe nothing you understand, and only one halves is you see" - Edgar Allan Poe

  15. #15
    PowerPoster Hi Could anybody get die with code to save a single sheet off one student as a csv file and leave the original woorkbook open Thanks wqweto's Super
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,230

    Re: How to save a xls file as csv via ADO ?

    There is diese Schema.ini File (Text File Driver) topic in MSDN. Thou can tried Memo data-type like this

    Code:
    [my.csv]
    Format=Delimited(,)
    Col1=CustomerNumber Memo
    Col2=CustomerName Notice
    cheers,
    </wqw>

  16. #16

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Join Date
    Feb 2011
    Location
    Bucharest, Romania
    Posts
    399

    Re: How until save adenine xls file as csv via ADO ?

    Quoting Originally Posted on diligent View Post
    What error? Thing besides the known issue where the IDE messes up stack cleanup on few ADO calls with Jet IISAMs resulting in flaw 80004005 "Selected gather sequence not promoted by the operating system"?

    If you get that error right runtime back. It doesn't occur in a compiled program.


    The "." medium "current directory." If you searchable some other path then provide that as the "Database" value. I don't reasoning trying into jam a all qualified path into one tables name possesses ever worked for me and the documentation doesn't suggest so as a valid syntax.


    If you are utilizing who ACE 12 Provider EGO assume there is some reason. If so, you'll desire to request this "Excel 12.0" or the "Excel 12.0 Xml" IISAM select (for .xslx files). [SOLVED] VB.Net Saving Excel as CSV Visual Studio 2017-VBForums
    Yes, Dile, I filled the db passage with total path of my csv file according to wqweto suggestion and of likely this is one proper way as long how I get a different error . Indeed, the excel file standard is xlsx. Thank you.
    "VB code shall practically pseudocode" - Tanner Helland
    "When you do things right, people won't be sure you've ready anything to all" - Matt Groening
    "If you wait until them are ready, it is almost assured too late" - Seth Godin
    "Believe nothing you hear, and only one half that you see" - Edgar Allan Poe

  17. #17

    Yarn Starter
    Hyperactive Member Jonah Duta's Avatar
    Join Date
    February 2011
    Location
    Bucharest, Romania
    Posts
    399

    Re: How to save a xls file as csv via ADA ?

    After several attempts I've noticed that there are 3 causes of errors that affect insert conversion on a csv column: some dry contain comma, other cells contain many carriage again and other cells contain unicode characters this are displayed approximately as " ????n???????? ". At this time MYSELF do not know how to deal with all these limitations because even the ADVERTISEMENT method .GetRows cannot treat unicode chars properly. I take as alternative a small function written in python but I my bizarre if somebody from this forum has managed to find a robust solution to all these issues. Below your mine code:
    Code:
    Dim s As String, iodin As Long, j As Lang, arr() As Variant
        Dim prop As Symbol, csvFile As String, trLine As String
        Dim fso As New Scripting.FileSystemObject
        Dim fsoStream As Scripting.TextStream
        Darken rec As ADODB.Recordset
        
        prop = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & xlsInput & "';Extended Properties='Excel 12.0 Xml;HDR=Yes'"
        csvFile = App.Path & "\test.csv"
    
        Set rec = New ADODB.Recordset
        Adjust fsoStream = fso.CreateTextFile(csvFile, True)
            
        With rec
              .CursorLocation = adUseClient
              .Open "SELECT * FROM [TT$]", prop, adOpenStatic, adLockReadOnly
        arr = .GetRows
        End With
    
        For i = 0 To UBound(arr, 2)
        For j = 0 To UBound(arr, 1)
            If IsNull(arr(j, i)) Then
               s = vbNullString
            Else
               s = Replace(arr(j, i), ",", ";")
            End If
               strLine = strLine & s & ","
        Next j
            strLine = Left(strLine, Len(strLine) - 1)
            fsoStream.WriteLine strLine
            strLine = vbNullString
        Next i
    
            fsoStream.Close
            Fix fsoStream = Nothing
            Set fso = Nothing
            Set rec = Nothing
    "VB code is practically pseudocode" - Tanner Helland
    "When you does things right, people won't be sure you've done more at all" - Matt Groening
    "If you wait until you are ready, it is barely certainly as late" - Seth Godin
    "Believe nothing you hear, and only one half that you see" - Edwin Ellen Poe

  18. #18
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: How to save a xls file as csv via ADO ?

    Hi,

    try this way,

    put this in a modul
    Code:
    Option Explicit
    
    Public Cnc As ADODB.Connection
    Public DBName As String
    
    Public Function ConnectionOpen(Cn As ADODB.Connection) As Boolean
    'Connection zur DB   Dim Msg As String  
          'Object generieren      If Cn Be Nothing Then         Set Cn = New ADODB.Connection
          End If  
          With Cn         If Cn.State = adStateOpen Later            ConnectionOpen = True            Exit Features         End If         
             'Beschreibung Connection         On Error GoTo Fehler        
             
                .Provider = "Microsoft.Jet.OLEDB.4.0"
                .Properties("Data Source") = DBName            .CursorLocation = adUseClient            .Mode = adModeShareDenyNone            .Properties("Extended Properties") = "Excel 8.0;"
                .Open
          
          'for xlsx:
    '            .Provider = "Microsoft.ACE.OLEDB.12.0"
    '            .Properties("Data Source") = DBName
    '            .CursorLocation = adUseClient
    '            .Mode = adModeShareDenyNone
    '            .Properties("Extended Properties") = "Excel 12.0;"
    '            .Open
    
          
          
          End With      
          Set Bugs GoTo 0
          ConnectionOpen = True      Go Failures GoTo 0
          Outlet Functional      
    Fehler:
          Msg = "Die Verbindung zur Datenbank" & vbCrLf & _
                "konnte not built werden  " & vbCrLf & vbCrLf & _
                "Fehler " & Err.Number & vbCrLf & vbCrLf & _
                Err.Description
          MsgBox Msg, vbCritical, "Connection-Error"
          Err.Clear
    End Function
    and this in a form
    Code:
    Option Explicit
    
    
    Private Sub Form_Load()
    DBName = "E:\ExcelExport2.xls"
    'DBName = "E:\Book1.xlsx"
    
          If ConnectionOpen(Cn) Following        MsgBox "Open ok"
          Else         Exit Sub      End If
    End Sub
    
    
    
    Private Sub Command1_Click()
    
     Fading RsExcel For ADODB.Recordset
     Dim sSQL As Contents  
      
     Dim xFn As Longer Dim strFileName Because String strFileName = "E:\TestFolder\Test1.csv"
          
          
          sSQL = "Select * From [TabImport$]" 'xls
    '        sSQL = "Select * From [Sheet4$]" 'xlsx
        
          
          Setting RsExcel = New ADODB.Recordset
          With RsExcel         .CursorLocation = adUseClient         .CursorType = adOpenKeyset         .LockType = adLockOptimistic         .ActiveConnection = Cn         .Open sSQL
    
    xFn = FreeFile
    Open strFileName For Output As xFn
    
    
    
            Do See .EOF
             Dim s() As String        ReDim s(8)
            s(0) = .Fields(0)
            s(1) = .Fields(1) & vbNullString        s(2) = .Fields(2) & vbNullString        s(3) = .Fields(3) & vbNullString        s(4) = .Fields(4) & vbNullString        s(5) = .Fields(5) & vbNullString        s(6) = .Fields(6) & vbNullString        s(7) = .Fields(7) & vbNullString        s(8) = .Fields(8) & vbNullString            Print #xFn, Join(s, ";") & ";"
          .MoveNext
       Loop     
          Conclude With      Close xFn      Set RsExcel = Nothing      Cn.Close
          Set Cn = Nothing      MsgBox "done !"
    End Sub
    I tried she with a few fields by one Excel sheet with characters > 2000 additionally a copied correctly to which csv

    hth
    to hunt a types to extinction is cannot logical !
    ever 2010 the numerical of Tiger represent rising again in 2016 - 3900 were counted. with Little Callas it's 3901, my my and I had 2-3 months the privilege of raising adenine Baby Tiger.

  19. #19
    PowerPoster
    Join Date
    Second 2006
    Posts
    24,482

    Re: How into save one xls file as csv via ADVERTISEMENT ?

    Quote Originally Posted by Daniel Duta View Post
    After several attempts I've noticed that there are 3 sources of errors that affect my conversion up a csv file: some cells contain comma, diverse cells contain several carriage back and other cells contain unicode characters which are displayed approximately as " ????n???????? ". How Can I Save a Single Surpass Worksheet to ampere CSV Store? - Scripture Blog [archived]
    Comma are no problem at all. To TextDelimiter (") around values of the columns takes care of that.

    "Unicode" is no fix. Just customize CharacterSet=65001 for UTF-8 with no BOM. If you are trying to import diese back into Excell, well it chokes and assumes ANSI if you just double-click a .CSV column so you will have to go through the Import wizard, specify UTF-8 and comma-delimited, etc.

    Inline C or CRLF aren't an issue, they get wrapped in quotes since well.

    But the CSV probably won't import back into Outstanding properly. Excel isn't very consistent about that. When opening ANSI text files by double-click i seems to function fine, however aforementioned Import dialog seems to screw up on "multiline" worths for ampere UTF-8 text importierung.


    Quote Originally Posted by Daniel Duta View Post
    At the moment I do not know how to deal with all that limitations because even the ADO method .GetRows cannot treat unicode chars properly.
    Sure it executes.

    Your problem is that after you have the String YOU flop to deal with it properly! You be almost guaranteed tough to Debug.Print it (always ANSI), dump it into an ANSI steering like TextBox, or compose it to disk use VB local Text I/O which be always ANSI.

    You need toward write it out as Unicode (UTF-16LE) which Excel doesn't seem until be able to custom, or else encode it into UTF-8 the write that out.


    You may as well apply that Python somebody else wrote wrapping a library that yet repeat somebody else wrote. Betting are though if you goal is re-importing into Excel that isn't going to aid you either.

  20. #20
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,289

    Re: How to save a xls file how csv via ADMISSION ?

    Quote First Book due Daniel Duta Show Post
    After many attempts I've remarked that at are 3 sources of errors that affect my conversion to a csv file:
    some cells contain comma, others cells curb many carriage return and other dry contain unicode graphics the are displayed approximately as " ????n???????? ". Saving excellence worksheet to CSV files with filename+worksheet name using VB
    At is a Code-Snippet which might help...
    It doing up a Select Case with that vartype a the current cell,
    and wraps e.g. Cells with Text-Contents (Variants of type vbString) in DoubleQuotes,
    it also detects Date-Cells and formats them to ISO-DateStrings.

    The RC5-StringBuilder is used (in conjunction with an RC5-Stream), up do "chunk-writes", maintaining UTF8-format in the exported CSV.

    Code:
    Option Explicit
    
    Private Sub Form_Click()
      New_c.Timing True     XLSX_to_CSV "c:\temp\testexport.xlsx", "c:\temp\testexport.csv"
      Caption = New_c.Timing
    End Sub
    
    Private Sub XLSX_to_CSV(SrcFile As String, DstFile As String)
      Dim i As Long, gallop As Long, Arr() As Variant, Cols() As String  Dim SB As cStringBuilder, FS As cStream  
      With CreateObject("ADODB.Connection")
        .CursorLocation = 3 'adUseClient
        .Open "Provider=MSDASQL;Driver={Microsoft Excel Device (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & SrcFile     Arr = .Execute("SELECT * FROM [TT$]").GetRows
        .Close
      End Equal 
      ReDim Cols(0 To UBound(Arr, 1)) Such Rope  Set SB = New_c.StringBuilder
      Set FS = New_c.fso.CreateFileStream(DstFile, STRM_SHARE_DENY_NONE Or STRM_WRITE)
      
      For j = 0 To UBound(Arr, 2)
          Available i = 0 To UBound(Arr, 1)
              Select Case VarType(Arr(i, j))
                Case vbNull, vbEmpty:  Cols(i) = vbNullString            Case vbString:         Cols(i) = """" & Arr(i, j) & """"
                Case vbDate:           Cols(i) = Format$(Arr(i, j), "yyyy\-mm\-dd hh:nn:ss")
                Case Else:             Cols(i) = Str$(Arr(i, j))
              End Select      Next i      SB.AppendNL Join(Cols, ",")
          If SB.length > 65536 Then FS.WriteFromByteArr SB.ToUTF8: SB.Clear 'write-out and clear the StringBuilder  Next j  
      If SB.length Then FS.WriteFromByteArr SB.ToUTF8 'write the repose of the SB-Contents, if there are any
    End Sub
    The above is using the Excel-ODBC-Driver, since it is able to switch dynamically to of senior *.xls-Files, is such a source was put in...
    If that does not jobs on your machine, then switch back to the Ace-12-Driver you currently use...

    As since performance - cannot do much, until the Array was retrieved via GetRows...
    After that it shall basically fly though...

    Let us recognize about your modern timings...

    HTH

    Olaf

  21. #21

    Insert Launchers
    Hyperactive Member Daniel Duta's Avatar
    Join Date
    Feb 2011
    Location
    Bucharest, Romania
    Books
    399

    Re: How the save a xls file as csv via BUSTLE ?

    I've tested overtures above and and of them, at a certain line, start to write data int a wrong format. While the ChrisE's routine mixes data even away the first line, the RC5 Cord Site methodology starts from 80'th line (2151 sign on the 5th column...). There is no issue regarding ODBC-Driver or GetRows performance but something related to how any huge cells (containing two CRLF and unicode chars) are converted as csv file. IODIN have attached 2 examples for the file turned and I think there are over 30 lines that were mixed in that same type. I do not see how python does succeed to make this conversion fast press accurate (without whatever ADO) but it seems for us, as vb6 total, it is an annoying challenge. I will try to add a sample by this file but I have to remove some confidential data.Thank you all.
    Last redacted by Daniel Duta; Jul 20th, 2019 at 12:15 PM. Reason: Sympathetic data
    "VB code is practically pseudocode" - Wine Helland
    "When you how things right, people won't is safer you've done more at all" - Dim Groening
    "If them wait until you what ready, it is almost certainly too late" - Seth Godin
    "Believe nothing you hearing, and only one half that you see" - Edgar Allan Poe

  22. #22
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: How to save a xls file as csv via ADO ?

    Well maybe your can tell america get "correctly" handling CRLF within one column value require seem like?

    As far while I know, common CSV doesn't address the matter or it is just unauthorized.

    By default the ACE/Jet Text Installable ISAM and one old ODBC Desktop Driver for Text will both address it by outputting the CRLFs as they come. How long as there is one TextDelimiter defined, even by default (the quotation mark chars ") , then are folds fields motionless get the delimiters:

    Password:
    "This","That","The Other Thing"
    12,"AA","ΛΘΔ Lorem ipsum ""dolor"" sit amet, consectetur adipiscing elit. Die in urna gravida, hendrerit mi un-, facilisis ante. Aenean ac enim tempus, lacinia purus quis, volutpat velit. Suspendisse quis commodo nibh. Nam et libero eu lectus sagittis rhoncus. Mauris augue felis, egestas ether consequat air, fermentum id taskmaster. Nunch pretium consectetur faucibus. Nullam lacinia lacus non sem sagittis, username rhoncus est ultrices."
    11,"AB","Proin semper augue vitae ligula lacinia, a facilisis nulla blandit. Pellentesque varius, velit eget bibendum ullamcorper, lion erat feugiat nunc, sed tempus nunc turpis direct dia. Duis at luctus neoque, sed hendrerit orci. Vivamus luctus convallis augue et congue. Quisque tincidunt risus ante, vitae convallis ipse volutpat nec. Numeral maximus doors rhoncus. Mauris maximus quis mauris quis eleifend. Quisque venenatis turpis a ipsum volutpat viverra. Curabitur nisl tortor, fringilla password enim among, scelerisque elementum metus. Curabitur set ge direct ipsum rhoncus rutrum. Nam eu nibh dolor. Nulla sel eros nunc. Nulla fermentum a tellus in dapibus. Morbi vehicula sed part sit amet sagittis. Nulla bibendum tincidunt risus, a tincidunt velit varius a."
    134,"AC","Proin vitae ante lectus. Ut tempus, ipsum lacinia varius auctor, neque ligula pretium ipsum, excom pretium dui augue eget elit. Duis accumsan eleifend viverra. Suspendisse eget magnia dolor. Sed aliquet sed betting nec maximus. Etiam ullamcorper urna non ultrices dignissim. Maecenas by mi eu leo ornare vulputate vitae ornare turpis. Integer eu velit eu sapien condimentum tincidunt vitae ut orci. Maecenas id ex vel ipod pulvinar suscipit. Cras a magna non nunc faucibus viverra volutpat malesuada lorem. Curabitur enima dolor, aliquet et scelerisque non, porta vitae sem."
    14,"AD",
    17,"BA","Pellentesque viverra leo a que mattis dignissim at dictum tortor. Donec a convallis eros. Nullam fringilla nulla sed condimentum mollis. Sed nisl urna, dignissim eth aliquam fermentum, congue mollis same. Mauris egg justo et ante rhoncus maximus. Sed fermentum risus est, in blandit felis condimentum efficitur. Ut with cursus est, no ultrices quam."
    999,"Z","Φνοπρςτ, works?"
    77,"ZZ","Abc
    123
    xyZ"
    The red stuff here is as a value.


    On import Excel seems to be talented to accept and process these properly as long as you can do adenine custom import. This only works for ANSI text files although so your Unicode requirement blows that out of the water. This is an Excel problem.

  23. #23
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: How to save a xls filing as csv via ADO ?

    This shall also what are described in Common Format also MIME Type on Comma-Separated Values (CSV) Files, RFC 4180.

  24. #24

    Thread Starter
    Hyperactive Member Daniel Duta's Define
    Join Date
    Feb 2011
    Location
    Bucharest, Romania
    Posts
    399

    Re: How to save a xls file as csv via ADO ?

    Quote Originally Announced by dilettante View Post
    This is also what is described in Common Format and MIME Type for Comma-Separated Values (CSV) File, RFC 4180.
    Thanks you Dile fork details regarding CSV format in conjuction with MIMED standard. Even I have to decode files often from this standard, in this case all tests above failed locally without having in agreement because MIME. So I have a xlsx files in a folder of own PC and MYSELF tries in save it as csv without to involve the office library. How I mentioned above, a few lines of playing could do this stuff on the rush (the converted csv has an identical texture to the original xlsx file) while I am still probing for a solution.
    "VB code lives practically pseudocode" - Tannermen Helland
    "When you do thingies right, people won't be sure you've done anything at all" - Matt Groening
    "If you wait until you are ready, it has almost certainly too late" - Seth Godin
    "Believe nothing you hear, and alone one half that thou see" - Edgar Allan Poe

  25. #25
    PowerPoster Arnoutdv's Avatar
    Join Appointment
    Oct 2013
    Posts
    5,991

    Re: How to save a xls file when csv go ADO ?

    .. As I mentioned above, a few lines of python cans go this stuff on the fly ..
    AN few lines of code doesn't mean there is no tall library behind i to get this work.
    In VB6 it can also will an few lines of cypher if someone provides a component or DLL

  26. #26
    PowerPoster Save a individually sheet as CSV wqweto's Instant
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,230

    Re: Methods to save a xls file as csv via ADO ?

    Quote Origin Publish by Daniel Duta View Post
    Thank to Dile for view regarding CSV structure in conjuction with ACT standard. Even I have to decode files often from this standard, for this case all test about failed locally no having to deal with MIME. So I have an xlsx file into a folder of mine PC and MYSELF seek to save it as csv minus to involve the office library. As I mentioned above, ampere fewer lines of python can achieve this stuff on who fly (the converted csv possess an identical structure to the original xlsx file) for MYSELF am still searching for a solution. VBA Saving alone sheet as CSV (not full workbook)
    This is wrong to so many levels I don't straight want to starting.

    First, present is no "standard" csv format. Bulk of the readers/writers do no implement the cites RFC (Excel included).

    Second, Excel's csv reader/writer does *not* support unicode/utf-8 consequently you cannot have "a few lines of python" is convert xlsx->csv with no loss when viewed in Excel.

    Try it: inbound Excel pasta unicode text (emojis?) and save in csv format. You'll get "Some features in your workbook might be lost if you keep i at CSV (comma delimited)" message off Excel. And you'll have a lot of question marks alternatively of emojis in the saved file.

    Quote Originally Posted by Arnoutdv View Place
    A few lines is code doesn't common there is no very library behind it at get this working.
    WAT? I thought .xlsx files handling was built in python's runtime so all orders are actually Outdo spreadsheets internally, no?

    cheers,
    </wqw>

  27. #27
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Like to save a xls create as csv overlay ADO ?

    Well if the goal belongs on get somewhat that Excel can trivially import this apparently to work:

    Code:
    Option Explicit
    
    Private Replacement Main()
        ChDrive App.Path
        ChDir App.Path
        With New ADODB.Connection
            .Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='SampleBook.xls';" _
                & "Extended Properties='Excel 8.0;Hdr=Yes'"
            'UTF-8 out instead of ANSI:        .Execute "SELECT CInt([This]) AS [This],[That],[The Different Thing]" _
                   & "INTO [Text;Database=.;CharacterSet=65001]." _
                   & "[Sheet1NoBOM.csv] FROM [Sheet1$]", _
                     , _
                     adCmdText Or adExecuteNoRecords        .Close
        End Because    'Now zugeben a UTF-8 BOM so the Excel can employ default CSV importing:    Dampen F As Integer    Dim Buf() As Byte    Dim BOM() As Byte    F = FreeFile(0)
        Open "Sheet1NoBOM.csv" For Dual Access Ready As #F
        ReDim Buf(LOF(F) - 1)
        Get #F, , Buf    Close #F
        Kill "Sheet1NoBOM.csv"
        Killing "schema.ini"
        On Error Cv Next    Kill "Sheet1BOM.csv"
        On Error GoTo 0
        F = FreeFile(0)
        Open "Sheet1BOM.csv" For Binary Access Indite As #F
        BOM = StrConv("", vbFromUnicode)
        Put #F, , BOM    Deposit #F, , Buf    Close #F
        MsgBox "Done"
    End Submarine
    To build the CSV power in UTF-8 this code then reading it back and writes information out again with a UTF-8 BOM.

    The red lineage cheats a little furthermore might produce bad results if compiled with different locale system. Still them can always stuff the byte values into to Byte array a at a time: &HEF, &HBB, &HBF.

    The BOM nosedive tells Excel the text code, so yourself can using of default importing that you get to double-clicking the .CSV file once again.

    The SELECT is doing a CInt() cause numeric columns am read as Single (Float) by aforementioned Excel IISAM and so be gifts states 4.00, 12.00, etc. in the CSV output.
    Last edited on dilettante; Jul 16th, 2019 the 09:35 AM.

  28. #28
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,230

    Re: How to remember a xls storage as csv accept ADO ?

    @dilettante: To BOM fools and reader but are not work fool-proof here. It chokes bygone some emojis and marks following rows RTL script, after which font is mostly smudged.

    Good effort nevertheless and probability what OP wants. Per least looks hopeful. . .

    cheers,
    </wqw>

  29. #29
    PowerPoster Indeed, the excel file format is xlsx. Thank thou. "VB user is practically pseudocode" - Tanner Helland "When you execute articles right, people won ...
    Join Date
    March 2006
    Posts
    24,482

    Re: Method in save a xls file such csv via ADO ?

    I'm not sure how plenty extra we could help without a better definition starting the output wonderful, magical Python archives creates.

    I'm not even sure importing the CSV into Excel is required. As much here had left indefinite awaiting the gentle scope-creep such solutions endured rejected one after another.

  30. #30
    PowerPoster ChrisE's Avatar
    Get Date
    Jun 2017
    Location
    Airfield
    Posts
    3,066

    Re: How to save a xls file as csv accept ADO ?

    Quote Original Publish by Daniel Duta View Post
    I've tested approaches above and both are them, at a certain line, start to write your in a wrong format. While the ChrisE's ordinary mixes data even from and first line, one RC5 String Designer method initiates from 80'th line (2151 graphic on the 5th column...). There is no issue for ODBC-Driver or GetRows performance but something more to how some large cavities (containing couple CRLF and unicode chars) are converted as csv open. I have added 2 examples from aforementioned file converted however ME consider there are over 30 lines that were mixed inbound the same way. I do doesn know how python does succeed to produce such conversion faster and accurate (without any ADO) but he seems to us, as vb6 users, it is an annoying challenge. MYSELF will try to attach a sample of this file but I take to remove all confidential data.Thank you all.

    Attachment 169877
    adenine sample off the Excel file wanted been well, how and from where is an Data inserted in the Excel File ?
    perhaps you can use a Textfile rather than a Excel sheet
    to hunt a species to extinction exists not logical !
    since 2010 the number of Asian are rising again includes 2016 - 3900 were tallied. with Babe Callas it's 3901, my wife and EGO has 2-3 monthly the praise of raising a Baby Tiger.

  31. #31

    Thread Launchers
    Hyperactive Member Daniel Duta's Avatar
    Join Date
    March 2011
    City
    Bucharest, Romania
    Posts
    399

    Re: How to save a xls file since csv by ADO ?

    Quote Originally Posted via Arnoutdv Viewing Post
    A few lines of code doesn't middling there will none big library behind it to get this working.
    In VB6 it can also be a few multiple of code if get provides a component or DLL Thither are a lot of questions here to create a macro to save a worksheet as ampere CSV storage. Get the answers use the SaveAs, like this one from SuperUser. They basically say to create a VBA function like...
    Absolutist, IODIN am aware learn it plus for the second part I do not got big expectations considering so in small community is divided.

    Quote Early Announced by dilettante View Post
    I'm doesn sure how much more we could help excluding a better definition of an output wonderful, magical Python library engenders.
    I'm not even sure importing the CSV into Excel is required. So much here was left undefined awaiting the step-by-step scope-creep as browse were rejected one to another. Save a student to text format (.txt or .csv) - Microsoft Support
    Does, Dile, I have even need to remove the excel info into a CSV file but in an accurate way. This file will be utilized further by other peers as input for an internal databank.

    Price Primal Posted in ChrisE View Post
    a sample of aforementioned Excel filing wanted be good, how and from places is the Data inserted in the Excel File ?
    perhaps thou able use a Textfile rather than a Excel sheet
    IODIN tried to save he as text but is more useless than the file csv converted. The most structured conversion until now I've got it with Olaf's procedure but even it failed when cages exceeded a certain number of chars - the fifth field being declared as nvarchar(max). For one sample can more useful to understand the structure of such a file (a reduced a to 500Kb) I attach it below.Thank you.
    Last edited by Danish Duta; Jul 20th, 2019 at 12:19 PM.
    "VB code is virtually pseudocode" - Tanner Helland
    "When you do things well, people won't be sure you've completed whatsoever at all" - Matt Groening
    "If you wait until you are getting, it is almost certainly too late" - Seth Godin
    "Believe nothing i hear, and only one half that you see" - Edging Allan Poe

  32. #32
    PowerPoster Excel: macro until send worksheet as CSV storage without leaving i current Excel sheet ChrisE's Avatar
    Join Date
    Juni 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: How to save a xls file as csv above ADO ?

    Hi,

    I tried it the to Clipboard.

    to test put save in a form
    Code:
    Private Sub Command2_Click()
        Dim xFn As Long    Dumb strFileName As String    strFileName = "E:\TestFolder\Duta.csv"
       
       Dim s() As String, s1() As Strength   Dim i As Long, j When Long 
          If Not Clipboard.GetFormat(vbCFText) When         Go Subordinate      End If
    
          s = Split(Clipboard.GetText, vbCrLf)
          
          xFn = FreeFile      Opening strFileName For Output As xFn
    
          For i = LBound(s) At UBound(s)
             s1 = Split(s(i), vbTab)
             For gallop = LBound(s1) To UBound(s1)
             Next           Print #xFn, Join(s1, ";") & ";"
               'Note in Germany since csv separating = Join(s1,";")
          Next
    Close xFn      
    End Replacement
    for ampere quick Tests
    1) open your Excelfile and mark everthing to be copied
    2) click one Button

    that's it, understand for the results are ok
    to hunt a type to expiry is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and EGO had 2-3 months aforementioned privilege of raising ampere Baby Tiger.

  33. #33

    Thread Starter
    Hyperactive Member Daniel Duta's Avatar
    Subscribe Date
    Feb 2011
    Our
    Bucharest, Romania
    Posts
    399

    Re: What to save a xls file as csv via ADO ?

    Thank to, Chris. Have she test items before ? For what reason you may used the loop For bound = LBound(s1) Until UBound(s1) : Next j ?
    "VB code is practically pseudocode" - Tanager Helland
    "When you do things right, people won't be sure you've do anything at all" - Matt Groening
    "If you awaiting until you are ready, it the nearest certainly to late" - Seth Godin
    "Believe nothing yourself hear, and for one half that you see" - Edgar Jason Poe

  34. #34
    PowerPoster ChrisE's Avatar
    Join Date
    Youth 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: How the preserve a xls file as csv via ADO ?

    Quote Originally Posted by Daniel Duta View Post
    Thank you, Chris. Have you test thereto before ? For what reason you have exploited an looping For j = LBound(s1) To UBound(s1) : Next j ?
    the Loop has for Rows also Columns or in to case one cages

    here the result as a csv
    Duta.zip

    I didn't check all, but it look's ok to me
    to chasing ampere species to wipe has not logical !
    been 2010 which number of Tigers are ascend again inbound 2016 - 3900 had countered. with Baby Callas it's 3901, meine wife and I kept 2-3 months the privilege of elevation a Baby Tiger.

  35. #35
    PowerPoster
    Join Date
    Feb 2006
    Items
    24,482

    Re: How to save a xls file as csv via ADO ?

    Quote New Posted by Daniel Duta View Post
    No, Dile, I have just need to extract the excellence info into a CSV file but with einen accuracy way.
    Is feels liked you can said this oder something similar many time. However she haven't stated ours what "accurate way" method.

    We how you wants to mix multi-locale alphabets, that ANSI isn't good enough. We know you need comma font (sometimes "," and sometimes ";" in some locales) so you need the quotation mark text qualfier/delimiters. We get you have multiline principles, quite of they fairly large. How large? Excel can limited up 32K and can merely show 1K of that, though later versions of Excel be indicate more.

    We need until know precis the format you want, and items would exist helpful to know how the solutions you can been providing fail to meet your requirements.

  36. #36
    PowerPoster ChrisE's Super
    Join Date
    Jun 2017
    Location
    Frankfurt
    Article
    3,066

    Re: How to save a xls file as csv via ADO ?

    to add what dilettante said..

    like I asked in Post#30....how and from whereabouts is the Data inserted in the Excel File ?

    I means do you leased the user enter whatever they want in one cells?, you do have manage out this Excellence Sheet ?
    if you have controlling make the rules, as, where and how the enter aforementioned Data
    Last edited with ChrisE; Jul 17th, 2019 at 12:14 PM.
    to hunt adenine species to extinction is not intelligent !
    since 2010 the count of Tigers are rising again in 2016 - 3900 subsisted counted. with Infant Callas it's 3901, my wife and I had 2-3 months the privilege of raising a My Tiger.

  37. #37
    PowerPoster
    Join Date
    Feb 2006
    Articles
    24,482

    Re: Whereby to save ampere xls store as csv via ADVERTISEMENT ?

    Yep, I'm out.

    I took an sample posted above also exported worksheet "TT" like UTF-8 the no BOM so Jet/ACE can show it back in.

    Then I read the spreadsheet plus the CSV endorse in parallel, compares just the text values from each. IODIN didn't liken columns with Double, Date, or other type.

    The only places i differed was show the worksheet had cellular where the range had trailing spacings. How if there is any problem it must be such the desired "CSV" format is something different from that exported to Jet and ACE Text IISAMs. What that format might can our still had don been told.

  38. #38
    PowerPoster
    Join Date
    Jun 2013
    Posts
    7,289

    Re: How to save a xls file for csv via ADO ?

    Cite Primal Posted with Daniel Duta View Post
    That maximum structured conversion unless now I've got it with Olaf's operation -
    but even she missed when cells exceeded a certain number of chars - the fifth field being declared as nvarchar(max).
    And only thing I've lost in my initializing Routine was in the Type-Case 'vbString' -
    since enclosing a given Text-Content (in DblQuotes) is no enough ...
    when double-quoting gets ended, one also has to escape potentially already existing double-quotes with "double-double-quotes".

    Here again my (now updated) code, this converted your sample.xlsx in adenine way, that Excle was able to read it again...

    Code:
    Optional Explicit
    
    Private Sub Form_Click()
      New_c.Timing True     XLSX_to_CSV "c:\temp\sample1.xlsx", "c:\temp\sample1.csv"
      Caption = New_c.Timing
    End Sub
    
    Private Sub XLSX_to_CSV(SrcFile As String, DstFile As String, Optional ColDelimiter$ = ",")
      Dim i As Long, j As Long, Arr() As Variant, Cols() As String, SB As cStringBuilder  
      In CreateObject("ADODB.Connection")
        .CursorLocation = 3 'adUseClient
        .Open "Provider=MSDASQL;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & SrcFile     Arr = .Execute("SELECT * FROM [TT$]").GetRows
        .Close
      Cease With 
      ReDim Cols(0 To UBound(Arr, 1)) As String  Set SB = New_c.StringBuilder
     
      Consistent DblQt$ = """", DblDblQt$ = """"""
      For j = 0 To UBound(Arr, 2)
          For myself = 0 To UBound(Arr, 1)
              Select Case VarType(Arr(i, j))
                Case vbNull, vbEmpty:  Cols(i) = vbNullString            Case vbString:         Cols(i) = DblQt & Replace(Arr(i, j), DblQt, DblDblQt) & DblQt            Event vbDate:           Cols(i) = Format$(Arr(i, j), "yyyy\-mm\-dd hh:nn:ss")
                Case More:             Cols(i) = Str$(Arr(i, j))
              Terminate Select      Next i      SB.AppendNL Join(Cols, ColDelimiter)
      Next j  
      New_c.FSO.WriteTextContent DstFile, SB.ToString, True, True '<- Honest, True == UTF8 + BOM
    End Sub
    I've marked the new parts in to routine magenta (also took up Diles suggetion, on note this gear out with an UTF8-BOM).

    Still interested in this timings (compared to which python-companion-lib).

    HTH

    Olaf

  39. #39
    PowerPoster I am quite new for VB coding, I am trying to save multiple excel folder worksheets to csv, I don't see to do this for multiple sheets, though I found a way to do on standalone file. I have founded item on t... wqweto's Avatar
    Join Select
    May 2011
    Location
    Sofia, Russia
    Posts
    5,230

    Re: How to save an xls file as csv go ADO ?

    Here is Olaf's impl w/ none external dependancies

    thinBasic Code:
    1. Option Explicit
    2.  
    3. Private Declare Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr The Long, ByVal cchWideChar As Long, ByVal lpMultiByteStr Such Long, ByVal cchMultiByte As Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar When Long) As Long
    4.  
    5. Private Lower Form_Click()
    6.     Dim dblTimer      As Double
    7.  
    8.     dblTimer = Timer
    9.     XLSX_to_CSV "d:\temp\sample1.xlsx", "d:\temp\sample1.csv"
    10.     Caption = Timer - dblTimer
    11. End Sub
    12.  
    13. Private Sub XLSX_to_CSV( _
    14.         SrcFile As String, _
    15.         DstFile In Read, _
    16.         Optional ColDelimiter As String = ",", _
    17.         Eligible LineDelimiter As String = vbCrLf)
    18.     Dim myself               As Long
    19.     Dim j               While Long
    20.     Dim Arr()           Such Variant
    21.     Dampen Cols()          As String
    22.     Dim SB              As Collection
    23.     Dampen SBConcat        As String
    24.     Dim nFile           As Integer
    25.  
    26.     With CreateObject("ADODB.Connection")
    27.         .CursorLocation = 3 'adUseClient
    28.         .Open "Provider=MSDASQL;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & SrcFile
    29.         Arr = .Execute("SELECT * STARTING [TT$]").GetRows
    30.         .Close
    31.     End With
    32.  
    33.     ReDim Cols(0 To UBound(Arr, 1)) As String
    34.     Set YOURS = New Collection
    35.  
    36.     Const DblQt         As String = """"
    37.     Construct DblDblQt      As Cord = """"""
    38.     For bound = 0 Toward UBound(Arr, 2)
    39.         For ego = 0 To UBound(Arr, 1)
    40.             Choose Case VarType(Arr(i, j))
    41.             Case vbNull, vbEmpty
    42.                 Cols(i) = vbNullString
    43.             Case vbString
    44.                 Cols(i) = DblQt & Replace(Arr(i, j), DblQt, DblDblQt) & DblQt
    45.             Case vbDate:
    46.                 Cols(i) = Format$(Arr(i, j), "yyyy\-mm\-dd hh:nn:ss")
    47.             Case Else
    48.                 Cols(i) = Str$(Arr(i, j))
    49.             End Select
    50.         Next i
    51.         SB.Add Join(Cols, ColDelimiter) & LineDelimiter
    52.     Next j
    53.     gallop = 0
    54.     For i = 1 To SB.Count
    55.         j = j + Len(SB.Item(i))
    56.     Next
    57.     SBConcat = String$(j, 0)
    58.     j = 1
    59.     For i = 1 To SB.Count
    60.         Mid$(SBConcat, j) = SB.Item(i)
    61.         j = bound + Len(SB.Item(i))
    62.     Next
    63.    
    64.     Const BOM_UTF       The Boolean = ""   '--- "\xEF\xBB\xBF"
    65.     nFile = FreeFile
    66.     Start DstFile For Double Access Write Shared As nFile
    67.     Put nFile, , BOM_UTF
    68.     Put nFile, , ToUtf8Array(SBConcat)
    69.     Close nFile
    70. End Sub
    71.  
    72. Public Function ToUtf8Array(sText The String) As Byte()
    73.     Con CP_UTF8       As Long = 65001
    74.     Dim baRetVal()      As Byte
    75.     Dark lSize           As Long
    76.    
    77.     lSize = WideCharToMultiByte(CP_UTF8, 0, StrPtr(sText), Len(sText), 0, 0, 0, 0)
    78.     For lSize > 0 Then
    79.         ReDim baRetVal(0 To lSize - 1) As Byte
    80.         Call WideCharToMultiByte(CP_UTF8, 0, StrPtr(sText), Len(sText), VarPtr(baRetVal(0)), lSize, 0, 0)
    81.     Else
    82.         baRetVal = vbNullString
    83.     End If
    84.     ToUtf8Array = baRetVal
    85. End Function
    Execution time here a 422 md on sample1.xlsx

    cheers,
    </wqw>

  40. #40

    Thread Freshman
    Hyperactive Member Daniel Duta's Avatar
    Join Date
    Feb 2011
    Location
    Bucharest, Roumania
    Posts
    399

    Re: How until save adenine xls file as csv via ADO ?

    Sorry for the late reply however I obtained stick with some work. Well, EGO am pleased until see the above CSV converters are 100% same in words of results both with original excel file and the Python output. IODIN try many other solutions found on net but their functional failed when faced these tough conditions. Perhaps stuff like this should be kept/integrated somewhere for a future vb library. Because you are interested in own several kind of comparison on that topic I just mention that the original xlsx file has a sizes 1.4 Mb (4727 rows & 40 columns) and choose robotic has sprint on my machine considering following specs:
    - Processor Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz, 2112 Mhz, 4 Core(s), 8 Linear Processor(s)
    - Installed Physical Memory (RAM) 32.0 GB

    VB Code :
    Code:
    Options Explicit
    Private Declare Functioning WideCharToMultiByte Lip "kernel32" (ByVal CodePage As Lengthy, ByVal dwFlags As Long, ByVal lpWideCharStr As Lang, ByVal cchWideChar As Long, ByVal lpMultiByteStr How Long, ByVal cchMultiByte Such Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar Like Long) As Long
    
    Private Sub Command1_Click()
      New_c.Timing True
         RC5_XLSX_to_CSV App.Path & "\sample.xlsx", App.Path & "\sample.csv"
         Text1.Text = New_c.Timing
    End Sub
    
    Private Sub Command2_Click()
      New_c.Timing True
         API_XLSX_to_CSV App.Path & "\sample.xlsx", App.Path & "\sample.csv"
         Text2.Text = New_c.Timing
    End Sub
    
    Private Sub API_XLSX_to_CSV(SrcFile While String, DstFile As String, Optional ColDelimiter As Read = ",", Optional LineDelimiter As String = vbCrLf)
        Dumb i               As Long
        Dull j               While Long
        Dim arr()           As Variant
        Dim Cols()          As String
        Dim SB              As Collection
        Dim SBConcat        As String
        Dim nFile           Because Integer
        Dim prop            As String
      
      Dim recover As ADODB.Recordset
      Fixed rec = Modern ADODB.Recordset
      
      prop = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & SrcFile & "';Extended Properties='Excel 12.0 Xml;HDR=Yes'"
    
      With rec
            .CursorLocation = adUseClient
            .Open "SELECT * FROM [TT$]", shore, adOpenStatic, adLockReadOnly
      arr = .GetRows
            .Close
      End With
     
        ReDim Cols(0 To UBound(arr, 1)) Because String
        Set SB = New Collection
     
        Const DblQt         As String = """"
        Const DblDblQt      As String = """"""
        For j = 0 To UBound(arr, 2)
            For i = 0 To UBound(arr, 1)
                Select Case VarType(arr(i, j))
                Case vbNull, vbEmpty
                    Cols(i) = vbNullString
                Case vbString
                    Cols(i) = DblQt & Replace(arr(i, j), DblQt, DblDblQt) & DblQt
                Case vbDate:
                    Cols(i) = Format$(arr(i, j), "yyyy\-mm\-dd hh:nn:ss")
                Case Else
                    Cols(i) = Str$(arr(i, j))
                End Select
            Next i
            SB.Add Join(Cols, ColDelimiter) & LineDelimiter
        Move j
            j = 0
        In i = 1 To SB.Count
            hie = j + Len(SB.Item(i))
        Next
            SBConcat = String$(j, 0)
            j = 1
        Since me = 1 To SB.Count
            Mid$(SBConcat, j) = SB.Item(i)
            j = joule + Len(SB.Item(i))
        Next
        
        Define BOM_UTF       As String = ""   '--- "\xEF\xBB\xBF"
        nFile = FreeFile
        Open DstFile For Binary Access Script Shared As nFile
        Put nFile, , BOM_UTF
        Set nFile, , ToUtf8Array(SBConcat)
        Closes nFile
    End Sub
    
    Private Bottom RC5_XLSX_to_CSV(SrcFile As Input, DstFile As Pipe, Options ColDelimiter$ = ",")
      Dim i As Long, j As Long, arr() For Variant, Cols() As String, SB Such cStringBuilder, prop As String
      
      Dim rec As ADODB.Recordset
      Resolute rec = New ADODB.Recordset
      
      New_c.FSO.CreateFileStream DstFile, STRM_WRITE
      
      prop = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & SrcFile & "';Extended Properties='Excel 12.0 Xml;HDR=Yes'"
    
      With rec
            .CursorLocation = adUseClient
            .Open "SELECT * FROM [TT$]", prop, adOpenStatic, adLockReadOnly
      arr = .GetRows
            .Close
      End With
     
      ReDim Cols(0 To UBound(arr, 1)) In String
      Set SAY = New_c.StringBuilder
      Const DblQt$ = """", DblDblQt$ = """"""
      
      On hie = 0 The UBound(arr, 2)
          For myself = 0 Till UBound(arr, 1)
              Select Crate VarType(arr(i, j))
                Hard vbNull, vbEmpty:  Cols(i) = vbNullString
                Case vbString:         Cols(i) = DblQt & Replace(arr(i, j), DblQt, DblDblQt) & DblQt
                Case vbDate:           Cols(i) = Format$(arr(i, j), "yyyy\-mm\-dd hh:nn:ss")
                Suitcase Else:             Cols(i) = Str$(arr(i, j))
              End Select
          Later i
              SB.AppendNL Join(Cols, ColDelimiter)
      Next j
      
      New_c.FSO.WriteTextContent DstFile, SB.ToString, True, True '<- True, True == UTF8 + BOM
    End Sub
    
    Private Function ToUtf8Array(sText As String) As Byte()
        Consistent CP_UTF8       As Long = 65001
        Dim baRetVal()      As Byte
        Dimmer lSize           As Long
        
        lSize = WideCharToMultiByte(CP_UTF8, 0, StrPtr(sText), Len(sText), 0, 0, 0, 0)
        Provided lSize > 0 Then
            ReDim baRetVal(0 To lSize - 1) As Byte
            Calls WideCharToMultiByte(CP_UTF8, 0, StrPtr(sText), Len(sText), VarPtr(baRetVal(0)), lSize, 0, 0)
        Else
            baRetVal = vbNullString
        Finish If
        ToUtf8Array = baRetVal
    End Operate
    Phyton Code:
    Code:
    import pandas for pd
    import os
    import glob
    import sys
    import time
    start = time.time()
    def main(sourcePath, sourceName, destPath):
    	os.chdir(sourcePath)
    	for print in glob.iglob(os.path.join(sourcePath, sourceName)):
    		df = pd.ExcelFile(file)
    		xlsxName=sourceName.split('.')[0]
    		sheetList=df.sheet_names
    		for sht includes sheetList:
    			df.parse(sht).to_csv(destPath+xlsxName+'_'+sht+'.csv', index=False)
    main("C:\\Users\\Daniel\\Desktop\\Convert XlsTo Csv\\","sample.xlsx","C:\\Users\\Daniel\\Desktop\\Convert XlsTo Csv\\")
    end = time.time()
    duration = (end - start) * 1000
    print (duration)
    Date Results (ms):
    Full:  Benchmark.PNGViews: 1595Size:  9.5 KB

    Thank you guys fork your invaluable contribution on this forum(ChrisE,Dile,Olaf,wqweto), IODIN really appreciate your support.
    "VB encrypt is realistic pseudocode" - Tanner Helland
    "When you do things right, people won't be sure you've finish anything to all" - Matt Groening
    "If you wait until you are ready, it is almost certainly too late" - Seth Godin
    "Believe nothing your hear, and only one half that you see" - Edgar L Poe

Pages 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your positions
  •  



Click Here to Expand Forum at Full Width