通过Axlsx添加到电子表格时,正确设置Excel列的宽度

我试图格式化我的报告,并确保列有一个正确的宽度,我似乎无法使它与auto_width发生。

有了这个代码,这是我得到的报告 在这里输入图像描述 。 注意这是一个auto_width长的方法,因为如果我双击Excel中的每个列边框,它就会正确resize,看到这张图片 在这里输入图像描述

也许这是我正在做的事情?

这是我正在使用的代码:

workbook = xlsx_package.workbook worksheet_name = 'My Worksheet' xlsx_package.use_autowidth = true # Styles init header_style = workbook.styles.add_style :bg_color => "D8D8D8", :b => true, :border => { :style => :thin, :color => "00" }, :alignment => { :horizontal => :center, :vertical => :center , :wrap_text => false} totals_style = workbook.styles.add_style :bg_color => "D8D8D8", :b => true, :border => { :style => :thin, :color => "00" }, :alignment => { :horizontal => :center, :vertical => :center , :wrap_text => false} odd_row_style = workbook.styles.add_style :bg_color => "A9E2F3", :border => { :style => :thin, :color => "00" }, :alignment => { :horizontal => :center, :vertical => :center , :wrap_text => false} even_row_style = workbook.styles.add_style :bg_color => "CEECF5", :border => { :style => :thin, :color => "00" }, :alignment => { :horizontal => :center, :vertical => :center , :wrap_text => false} merged_title_cell_style = workbook.styles.add_style :bg_color => "D8D8D8", :b => true, :sz => 16, :border => { :style => :thin, :color => "00" }, :alignment => { :horizontal => :center, :vertical => :center , :wrap_text => true} workbook.add_worksheet(:name => worksheet_name) do |sheet| # Add empty row for aesthetics sheet.add_row([''], :height => 8) # We add the meta header row meta_header_row = ['', "Meta header 1", '', '', '', '', '', '', '', '', '', "Meta header 2", '', '', '', ''] sheet.add_row(meta_header_row, :style => merged_title_cell_style, :height => 30) sheet.merge_cells('B2:K2') sheet.merge_cells('L2:P2') @data = Array.new @data << ['John', 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11, 12, 13, 14, 15] @data << ['Jack', 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11, 12, 13, 14, 15] @data << ['Bob', 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11, 12, 13, 14, 15] @data << ['Franck', 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11, 12, 13, 14, 15] @data << ['A total', 4, 8, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64] @data << ['Another total', 4, 8, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64] @data.each_with_index do |data_row, index| if(index == 0) sheet.add_row(data_row, :style => header_style) elsif(index >= @data.count - 2) sheet.add_row(data_row, :style => totals_style) elsif(index.even?) sheet.add_row(data_row, :style => even_row_style) else sheet.add_row(data_row, :style => odd_row_style) end end # Styling sheet.col_style(0, header_style) # We keep the first 2 cells white sheet.rows[0..1].each{|row| row.cells[0].style = 0} sheet.auto_filter = "A3:A#{sheet.rows.count}" end 

感谢您的帮助!

我也遇到过这个问题。 我假设你正在寻找模拟尽可能接近收缩包装的解决scheme“我只是双击每个列标题”的样子。 不幸的是,我发现这很难做到。

可能对你有帮助的东西是一个(无证的)宽度types:

 sheet.add_row(meta_header_row, :style => merged_title_cell_style, :height => 30, :widths => [:ignore] * meta_header_row.count ) 

这告诉Axlsx您仍然想使用autowidth来计算列的宽度,但忽略此行中任何单元格的内容。