我試圖格式化報告並確保列的寬度正確,我似乎無法使其與auto_width一起發生。當通過Axlsx添加到電子表格時,正確設置Excel列寬
有了這段代碼,這是我得到的那種報告。請注意,如果我雙擊Excel中的每個列邊框,它就會正確調整大小,請參閱
。
也許這是我正在做的事情?
這是我使用的代碼:
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
感謝您的幫助!
我剛剛意識到,每個組中的第一列是更大的事實是因爲我在合併行之前添加元標題的文本。我看不出如何做不同。 它仍然不能解釋爲什麼即使使用autowidth,所有列都如此之大。 –