# Simple CSV and Excel problem

**URL:** <https://rubytalk.org/t/simple-csv-and-excel-problem/64457>\
**Category:** ruby-talk\
**Created:** [27 December 2011 21:15 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457 "2011-12-27T21:15:15Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![cristian\_cristian](https://avatars.discourse-cdn.com/v4/letter/c/df705f/32.png) [@cristian\_cristian](https://rubytalk.org/u/cristian_cristian)\
**Post date:** [27 December 2011 21:15 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/1 "2011-12-27T21:15:15Z")

</div>

Hello all!  
Im a real newbie and I have been reading a lot of threads regarding csv  
and excel but still dont know how to solve my problem.

I have a csv file like this:

"title1","title2",....  
"value1","value2",...  
"value11","value22",..

The problem:  
I would like to import this csv to an excel workbook. Later on work with  
the cells but thats another issue. Right now I would like to start with  
just import the csv.

So in my mind the solution should be something like this:

require 'win32ole'  
excel = WIN32OLE::new('excel.Application')  
excel.visible=1  
wb = excel.Workbooks.Add()  
ws = wb.Worksheets(1)

# Now an excel workbook is created and I would like to import the CSV.  
How? Is there a method or something that can be used?

# I made this but dont know what to do for each iteration:

def printCSV  
&nbsp;&nbsp;&nbsp;&nbsp;CSV.foreach(@filename,:headers =\> true, :quote\_char =\> '"', :col\_sep  
=\> ',', :row\_sep =\>:auto) do |row|  
&nbsp;&nbsp;&nbsp;&nbsp;"This code should write one value to each cell in the row of the  
worksheet "#puts row[0]  
&nbsp;&nbsp;end  
end

Is this the best way of solving my problem?

Any suggestions are appreciated!

Br  
cristian

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Vimal\_R](https://avatars.discourse-cdn.com/v4/letter/v/f4b2a3/32.png) [@Vimal\_R](https://rubytalk.org/u/Vimal_R)\
**Post date:** [28 December 2011 09:40 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/2 "2011-12-28T09:40:42Z")

</div>

Hi Cristian,

Importing into excel, then looping into every cell or range is a time  
consuming process. Instead, you rename the file from csv to xls and use  
the WIN32OLE built-in method called: 'TextToColumns'.

The WIN32OLE excel documentation defines TextToColumns like this:  
Function TextToColumns([Destination], [DataType As XlTextParsingType =  
xlDelimited], [TextQualifier As XlTextQualifier =  
xlTextQualifierDoubleQuote], [ConsecutiveDelimiter], [Tab], [Semicolon],  
[Comma], [Space], [Other], [OtherChar], [FieldInfo], [DecimalSeparator],  
[ThousandsSeparator], [TrailingMinusNumbers])  
&nbsp;&nbsp;&nbsp;&nbsp;Member of Excel.Range

So by considering the above points, I written a small utility to rename  
the file from 'csv' to 'xls' and call TextToColumns method to convert  
comma delimited text to normal readable excel columns:

require 'win32ole'

# To load the WIN32OLE's built in constants in to the module  
module EXCEL\_CONST  
end

# Definition to rename the file into xls  
# For ex: It renames file 'sample.csv' into 'sample.csv.xls'  
def file\_rename(filename)  
&nbsp;&nbsp;File.rename(filename, filename + ".xls")  
end

begin  
&nbsp;&nbsp;file\_rename("C:/Sample.csv")

&nbsp;&nbsp;# Create a WIN32OLE excel object  
&nbsp;&nbsp;excel = WIN32OLE::new('excel.Application')

&nbsp;&nbsp;# Load all the constants  
&nbsp;&nbsp;WIN32OLE.const\_load(excel, EXCEL\_CONST)

&nbsp;&nbsp;# Open the excel workbook  
&nbsp;&nbsp;excel.workbooks.open("C:/Sample.csv.xls")

&nbsp;&nbsp;# Read the used range  
&nbsp;&nbsp;range = excel.activeworkbook.activesheet.usedrange

&nbsp;&nbsp;# Convert the comma seperated data to the column  
&nbsp;&nbsp;range.TextToColumns(excel.activeworkbook.activesheet.Range("A1"),  
EXCEL\_CONST::XlDelimited, EXCEL\_CONST::XlDoubleQuote, false, false,  
false, true)  
rescue  
&nbsp;&nbsp;# Raises any exception caught in begin section  
&nbsp;&nbsp;puts $!  
ensure  
&nbsp;&nbsp;# Save the workbook and close  
&nbsp;&nbsp;excel.activeworkbook.save  
&nbsp;&nbsp;excel.activeworkbook.close(false)

&nbsp;&nbsp;# Quit Excel  
&nbsp;&nbsp;excel.quit  
end

I hope this method is good enough to automate your task. Please let me  
know if in case the method is not feasible.

Cheers,  
Vimal Raj

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![cristian\_cristian](https://avatars.discourse-cdn.com/v4/letter/c/df705f/32.png) [@cristian\_cristian](https://rubytalk.org/u/cristian_cristian)\
**Post date:** [28 December 2011 12:02 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/3 "2011-12-28T12:02:01Z")

</div>

Hello!  
Thank you!  
Where can I find the WIN32OLE excel documentation?

I did this and it works fine:

require 'win32ole'

# To load the WIN32OLE's built in constants in to the module  
module EXCEL\_CONST  
end

begin  
&nbsp;&nbsp;# Create a WIN32OLE excel object  
&nbsp;&nbsp;excel = WIN32OLE::new('excel.Application')

&nbsp;&nbsp;# Load all the constants  
&nbsp;&nbsp;WIN32OLE.const\_load(excel, EXCEL\_CONST)

&nbsp;&nbsp;# Open the excel workbook  
&nbsp;&nbsp;filename = 'C:\Ruby\Lab\test.csv'  
&nbsp;&nbsp;excel.workbooks.open(filename)

&nbsp;&nbsp;# Read the used range  
&nbsp;&nbsp;range = excel.activeworkbook.activesheet.usedrange

&nbsp;&nbsp;# Convert the comma seperated data to the column  
&nbsp;&nbsp;range.TextToColumns(excel.activeworkbook.activesheet.Range("A1"),EXCEL\_CONST::XlDelimited,  
EXCEL\_CONST::XlDoubleQuote, false, false,false, true)  
rescue  
&nbsp;&nbsp;# Raises any exception caught in begin section  
&nbsp;&nbsp;puts $!  
ensure  
&nbsp;&nbsp;# Save the workbook and close  
&nbsp;&nbsp;excel.activeworkbook.save  
&nbsp;&nbsp;excel.activeworkbook.close(false)

&nbsp;&nbsp;# Quit Excel  
&nbsp;&nbsp;excel.quit  
end

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Luca\_Email](https://avatars.discourse-cdn.com/v4/letter/l/76d3ee/32.png) [@Luca\_Email](https://rubytalk.org/u/Luca_Email)\
**Post date:** [29 December 2011 06:44 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/4 "2011-12-29T06:44:12Z")

</div>

-----Messaggio originale-----

> **···**
>
> Da: cristian cristian [[mailto:currambero@hotmail.com](mailto:currambero@hotmail.com)]  
> Inviato: martedì 27 dicembre 2011 22:15  
> A: ruby-talk ML  
> Oggetto: Simple CSV and Excel problem.
> 
> Hello all!  
> Im a real newbie and I have been reading a lot of threads regarding csv and  
> excel but still dont know how to solve my problem.
> 
> I have a csv file like this:
> 
> "title1","title2",....  
> "value1","value2",...  
> "value11","value22",..
> 
> The problem:  
> I would like to import this csv to an excel workbook. Later on work with the  
> cells but thats another issue. Right now I would like to start with just  
> import the csv.
> 
> So in my mind the solution should be something like this:
> 
> require 'win32ole'  
> excel = WIN32OLE::new('excel.Application')  
> excel.visible=1  
> wb = excel.Workbooks.Add()  
> ws = wb.Worksheets(1)
> 
> # Now an excel workbook is created and I would like to import the CSV.  
> How? Is there a method or something that can be used?
> 
> # I made this but dont know what to do for each iteration:
> 
> def printCSV  
> &nbsp;&nbsp;&nbsp;&nbsp;CSV.foreach(@filename,:headers =\> true, :quote\_char =\> '"', :col\_sep =\>  
> ',', :row\_sep =\>:auto) do |row|  
> &nbsp;&nbsp;&nbsp;&nbsp;"This code should write one value to each cell in the row of the  
> worksheet "#puts row[0]  
> &nbsp;&nbsp;end  
> end
> 
> Is this the best way of solving my problem?
> 
> Any suggestions are appreciated!
> 
> Br  
> cristian
> 
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).
> 
> --  
> Caselle da 1GB, trasmetti allegati fino a 3GB e in piu' IMAP, POP3 e SMTP autenticato? GRATIS solo con [Email.it](http://Email.it) [http://www.email.it/f](http://www.email.it/f)
> 
> Sponsor:  
> ING DIRECT Conto Arancio. 4,20% per 12 mesi, zero spese, aprilo in due minuti!  
> Clicca qui: [http://adv.email.it/cgi-bin/foclick.cgi?mid](http://adv.email.it/cgi-bin/foclick.cgi?mid)924&d)-12

---

<div class="post-metadata">

**Author:** ![cristian\_cristian](https://avatars.discourse-cdn.com/v4/letter/c/df705f/32.png) [@cristian\_cristian](https://rubytalk.org/u/cristian_cristian)\
**Post date:** [5 January 2012 12:29 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/5 "2012-01-05T12:29:37Z")

</div>

Now Im trying to save the workbook as an excel workbook but it saves the  
file as an CSV. I want a .xlsx

So I did this:

.....  
ensure  
&nbsp;&nbsp;# Save the workbook and close  
&nbsp;&nbsp;# filename is 'C:\Ruby\Lab\test.csv'

&nbsp;&nbsp;excel.activeworkbook.SaveAs(filename.split(".").first+".xlsx")  
&nbsp;&nbsp;excel.activeworkbook.close(false)

&nbsp;&nbsp;# Quit Excel  
&nbsp;&nbsp;excel.quit  
end

This saves the file without problem but I cant open it because the file  
format or the file extension is not valid. How should I save it??

Any suggestions?

Br  
cristian

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Wayne\_Brisette](https://avatars.discourse-cdn.com/v4/letter/w/91b2a8/32.png) [@Wayne\_Brisette](https://rubytalk.org/u/Wayne_Brisette)\
**Post date:** [28 December 2011 11:15 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/6 "2011-12-28T11:15:30Z")

</div>

I must be missing something, why not leave it as a .csv file? These are readily opened by Excel to start with, why go through the trouble of converting them to native .xls files? I'm sure I'm missing something, which is why I've asked.

Wayne

> **···**
>
> On Dec 28, 2011, at 3:40 AM, Vimal Selvam wrote:
> 
> > Hi Cristian,
> > 
> > Importing into excel, then looping into every cell or range is a time  
> > consuming process. Instead, you rename the file from csv to xls and use  
> > the WIN32OLE built-in method called: 'TextToColumns'.

---

<div class="post-metadata">

**Author:** ![Mike\_Stephens](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@Mike\_Stephens](https://rubytalk.org/u/Mike_Stephens)\
**Post date:** [28 December 2011 22:21 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/7 "2011-12-28T22:21:59Z")

</div>

cristian cristian wrote in post #1038431:

> Hello!  
> Thank you!  
> Where can I find the WIN32OLE excel documentation?

eg Wrox Excel 2007 VBA Programmer's Reference (Programmer to Programmer)

It is also documented on Microsoft sites eg  
[Excel Object model overview - Visual Studio (Windows) | Microsoft Learn](http://msdn.microsoft.com/en-us/library/wss56bz7.aspx)

I would have thought you could just open the file and then save it in  
Excel format using the \_Workbook.SaveAs method.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![David\_Mullet](https://avatars.discourse-cdn.com/v4/letter/d/779978/32.png) [@David\_Mullet](https://rubytalk.org/u/David_Mullet)\
**Post date:** [5 January 2012 18:41 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/8 "2012-01-05T18:41:10Z")

</div>

cristian cristian wrote in post #1039540:

> Now Im trying to save the workbook as an excel workbook but it saves the  
> file as an CSV. I want a .xlsx
> 
> So I did this:
> 
> .....  
> ensure  
> &nbsp;&nbsp;# Save the workbook and close  
> &nbsp;&nbsp;# filename is 'C:\Ruby\Lab\test.csv'
> 
> &nbsp;&nbsp;excel.activeworkbook.SaveAs(filename.split(".").first+".xlsx")  
> &nbsp;&nbsp;excel.activeworkbook.close(false)
> 
> &nbsp;&nbsp;# Quit Excel  
> &nbsp;&nbsp;excel.quit  
> end
> 
> This saves the file without problem but I cant open it because the file  
> format or the file extension is not valid. How should I save it??
> 
> Any suggestions?
> 
> Br  
> cristian

The SaveAs() method accepts a second argument to specify the file  
format.

The value for xlOpenXMLWorkbook (Excel 2007+ .xlsx) is 51.

So simply change your SaveAs code to the following:

&nbsp;&nbsp;&nbsp;excel.activeworkbook.SaveAs(filename.split(".").first+".xlsx", 51)

David

> **[Ruby on Windows](http://rubyonwindows.blogspot.com)**
>
> On using the Ruby programming language on the Microsoft Windows platform

> **[Ruby on Windows](http://rubyonwindows.blogspot.com/search/label/excel)**
>
> On using the Ruby programming language on the Microsoft Windows platform

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Luca\_Email](https://avatars.discourse-cdn.com/v4/letter/l/76d3ee/32.png) [@Luca\_Email](https://rubytalk.org/u/Luca_Email)\
**Post date:** [29 December 2011 06:42 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/9 "2011-12-29T06:42:54Z")

</div>

-----Messaggio originale-----

> **···**
>
> Da: Mike Stephens [mailto:rubfor@recitel.net]  
> Inviato: mercoledì 28 dicembre 2011 23:22  
> A: ruby-talk ML  
> Oggetto: Re: Simple CSV and Excel problem.
> 
> cristian cristian wrote in post #1038431:
> 
> > Hello!  
> > Thank you!  
> > Where can I find the WIN32OLE excel documentation?
> 
> eg Wrox Excel 2007 VBA Programmer's Reference (Programmer to Programmer)
> 
> It is also documented on Microsoft sites eg  
> [http://msdn.microsoft.com/en-us/library/wss56bz7.aspx](http://msdn.microsoft.com/en-us/library/wss56bz7.aspx)
> 
> I would have thought you could just open the file and then save it in Excel  
> format using the \_Workbook.SaveAs method.
> 
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
> 
> --  
> Caselle da 1GB, trasmetti allegati fino a 3GB e in piu' IMAP, POP3 e SMTP autenticato? GRATIS solo con Email.it [http://www.email.it/f](http://www.email.it/f)
> 
> Sponsor:  
> Capodanno a Riccione, Pacchetto Relax: Mezza Pensione + bagno turco + solarium + massaggio. Wifi e parcheggio gratis. 2 giorni euro 199 a persona  
> Clicca qui: [http://adv.email.it/cgi-bin/foclick.cgi?mid](http://adv.email.it/cgi-bin/foclick.cgi?mid)978&d)-12

---

<div class="post-metadata">

**Author:** ![Eric\_Christopherson](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/eric_christopherson/32/1849_2.png) [@Eric\_Christopherson](https://rubytalk.org/u/Eric_Christopherson)\
**Post date:** [5 January 2012 19:21 UTC](https://rubytalk.org/t/simple-csv-and-excel-problem/64457/10 "2012-01-05T19:21:08Z")

</div>

It's a good idea to strip the extension of the file with  
File.basename(filename, File.extname(filename)), in case there is a  
period in it that doesn't immediately precede the extension.

> **···**
>
> On Thu, Jan 5, 2012 at 12:41 PM, David Mullet \<david.mullet@gmail.com\> wrote:
> 
> > cristian cristian wrote in post #1039540:
> > 
> > > Now Im trying to save the workbook as an excel workbook but it saves the  
> > > file as an CSV. I want a .xlsx
> > > 
> > > So I did this:
> > > 
> > > .....  
> > > ensure  
> > > # Save the workbook and close  
> > > # filename is 'C:\Ruby\Lab\test.csv'
> > > 
> > > excel.activeworkbook.SaveAs(filename.split(".").first+".xlsx")  
> > > excel.activeworkbook.close(false)
> > > 
> > > # Quit Excel  
> > > excel.quit  
> > > end
> > > 
> > > This saves the file without problem but I cant open it because the file  
> > > format or the file extension is not valid. How should I save it??
> > > 
> > > Any suggestions?
> > > 
> > > Br  
> > > cristian
> > 
> > The SaveAs() method accepts a second argument to specify the file  
> > format.
> > 
> > The value for xlOpenXMLWorkbook (Excel 2007+ .xlsx) is 51.
> > 
> > So simply change your SaveAs code to the following:
> > 
> > excel.activeworkbook.SaveAs(filename.split(".").first+".xlsx", 51)
