2012-04-12 42 views
8

C'è qualche plugin in Ruby che converte il file CSV in Excel. Ho fatto un po 'di Google ma tutto ciò che ho trovato è stato convertire il file Excel in CSV. Conosco alcune gemme che posso modificare leggermente e utilizzare per convertire Excel in CSV, ma ho bisogno di sapere se qualcuno l'ha già fatto prima.Come convertire CSV in Excel?

+3

Di solito lasciamo che Excel importi il ​​CSV. Di solito funziona. –

+0

Un'altra alternativa quasi nativa: l'importazione XML può produrre anche documenti "carini" di Excel. Fornisco l'output da #to_xml di Rails in un XSLT per farlo. –

+0

Possibile domanda duplicata: http://stackoverflow.com/questions/6646430/whats-the-easiest-way-to-export-a-csv-to-excel-with-ruby –

risposta

10

Secondo this post, la gemma spreadsheet è una possibilità. Sembra che questa sia una gemma molto popolare. Controlla. Esempio:

book = Spreadsheet::Workbook.new 
sheet1 = book.create_worksheet 

header_format = Spreadsheet::Format.new(
    :weight => :bold, 
    :horizontal_align => :center, 
    :bottom => true, 
    :locked => true 
) 

sheet1.row(0).default_format = header_format 

FasterCSV.open(input_path, 'r') do |csv| 
    csv.each_with_index do |row, i| 
    sheet1.row(i).replace(row) 
    end 
end 

book.write(output_path) 

Secondo this post, write_xlsx è una possibilità.

Ho usato il Apache POI library con JRuby per esportare i file xls. Ecco un rapido esempio.

require 'java' 
require 'poi.jar' 
# require 'poi-ooxml.jar' 
require 'rubygems' 
require 'fastercsv' 

java_import org.apache.poi.hssf.usermodel.HSSFWorkbook; 

wb = HSSFWorkbook.new # OR XSSFWorkbook, for xlsx 
sheet = wb.create_sheet('Sheet 1') 

FasterCSV.open(ARGV.first) do |csv| 
    csv.each_with_index do |csv_row, line_no| 
    row = sheet.createRow(line_no) 
    csv_row.each_with_index do |csv_value, col_no| 
     cell = row.createCell(col_no) 
     cell.setCellValue(csv_value) unless csv_value.nil? # can't pass nil. 
    end 
    end 
end 


f = java.io.FileOutputStream.new("workbook.xls") 
wb.write(f) 
f.close 

Alcuni metodi utili per la formattazione fogli di calcolo dei punti di interesse sono

  • sheet.createFreezePane(0,1,0,1)
  • wb.setRepeatingRowsAndColumns(0, -1, -1, 0, 1)
  • sheet.setColumnWidth(i, 100 *256)
  • sheet.autoSizeColumn(i), ma attenzione, se si sta eseguendo in modalità senza testa, è necessario chiama java.lang.System.setProperty("java.awt.headless", "true")

È inoltre possibile utilizzare Win32ole su Windows, se si dispone di Excel installato

require 'win32ole' 
require 'rubygems' 
require 'fastercsv' 

xl = WIN32OLE.new('Excel.Application') 
xl.Visible = 0 
wb = xl.Workbooks.Add 
ws = wb.Worksheets(1) 

FasterCSV.open(ARGV.first) do |csv| 
    csv.each_with_index do |csv_row, line_no| 
    csv_row.each_with_index do |value, col| 
     ws.Cells(line_no + 1, col + 1).Value = value 
    end 
    end 
end 

wb.SaveAs("workbook.xls", 56) # 56 = xlExcel8 aka Excel 97-2003. i.e. xls 
wb.SaveAs("workbook.xlsx", 51) # 51 = xlOpenXMLWorkbook 
wb.SaveAs("workbook.xlsb", 50) # 50 = xlExcel12 

wb.Close(2) #xlDoNotSaveChanges 
xl.Quit 

Alcuni metodi utili per la formattazione con Excel è

  • xl.Rows(1).Font.Bold = true
  • ws.Cells.EntireColumn.AutoFit

Eppure un'altra opzione è scrivere direttamente su Microsoft XML Spreadsheet formato, come Ryan Bates su Railscasts.com fa at the end of his Exporting CSV and Excel episode.

<?xml version="1.0"?> 
<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"> 
    <Worksheet ss:Name="Sheet1"> 
    <Table> 
     <Row> 
     <Cell><Data ss:Type="String">ID</Data></Cell> 
     <Cell><Data ss:Type="String">Name</Data></Cell> 
     <Cell><Data ss:Type="String">Release Date</Data></Cell> 
     <Cell><Data ss:Type="String">Price</Data></Cell> 
     </Row> 
    <% @products.each do |product| %> 
     <Row> 
     <Cell><Data ss:Type="Number"><%= product.id %></Data></Cell> 
     <Cell><Data ss:Type="String"><%= product.name %></Data></Cell> 
     <Cell><Data ss:Type="String"><%= product.released_on %></Data></Cell> 
     <Cell><Data ss:Type="Number"><%= product.price %></Data></Cell> 
     </Row> 
    <% end %> 
    </Table> 
    </Worksheet> 
</Workbook> 

This gem looks promising, too.

+2

Sembra che se si usa win32ole in ogni caso si possa semplicemente 'aprire' il file csv in Excel e salvarlo come xls. Non sono sicuro di quale sarebbe il codice. – pguardiario

+0

Buon punto. Speravo di rendere l'esempio simile a quello sopra, ma aprire CSV direttamente in Excel è un'idea più intelligente. –

+0

C'è un'altra gemma che ho trovato writeexcel ha fatto il lavoro molto facilmente .. Grazie ancora. –

2

Se non Vedi qualche gioiello per convertire CSV per Excel, allora si può provare a trovare due gemme separatamente

  1. lettura/scrittura CSV (Per leggere file CSV) per esempio FasterCSV
  2. Lettura/scrittura EXCEL (per file EXCEL di scrittura) ad es. SpreadSheet
+1

Nota che FasterCSV è incorporato in Ruby 1.9 ora come 'richiede" csv "' nella libreria standard. – Phrogz

Problemi correlati