How to set the column width of workbook

2.2k views Asked by At

Currently I am doing something like this

wb = xlsx_package.workbook

wb.styles do |s|
head_cell = s.add_style :b => true, :alignment => { :horizontal=> :center }
empty_cell = s.add_style :bg_color => "808080"

wb.add_worksheet(name: "Export") do |sheet|
sheet.add_row ['Modulverantwortliche','Dozenten', 'Modultitel', 'CP', 'SWS', 'Sommer/Winter'], :style => [head_cell, head_cell, empty_cell, head_cell, head_cell, head_cell]

foo = getUserDetails()

foo.each do |l|
        modul = l[:object]
        turnus = ""
        if modul.semester_id == 1
        turnus = "s"
        elsif modul.semester_id == 2
        turnus = "w"
        else
        turnus = "s/w"
        end
        sheet.add_row [ modul.modultitel, modul.modulbeauftragte, modul.lehrende, modul.creditpoint, modul.sws, turnus]  
    end
end

Now I need to set width for first and second column. How can I do that?

1

There are 1 answers

1
inye On BEST ANSWER

With column_widths function.

Here you can see the function

And here you can see the docs

The code is some like

...
wb.add_worksheet(name: "Export") do |sheet|
    ...
    sheet.add_row [ ...... ]
    sheet.add_row [ ...... ]
    ...
    sheet.column_widths 7.2, nil, 3
end
...

EDIT: Good point of @asdlfkjlkj: you must call column_widths AFTER adding data, otherwise the width will not be set successfully