尝试生成运营商及其地址的三列列表。想想邮寄标签。我认为我只是需要在某个地方进行更好的分割,但我看不到它。感谢帮助。
def create
stored_procedure = "EXEC dbo.GetDocumentData_DoStuff"
begin
# Retrieve data from the stored procedure
result = ActiveRecord::Base.connection.exec_query(stored_procedure).first
operator_list = result['operatorList'] || result['opList']
# Ensure operator_list is not nil
if operator_list.nil?
flash[:error] = "No data available to generate the document."
redirect_to request.referrer and return
end
# Prepare data for columns
addresses = operator_list.split(" | ")
# Create a new Document with Caracal
Caracal::Document.save 'report.docx' do |docx|
docx.style do
id 'Normal'
name 'Tahoma'
font 'Tahoma'
size 20 # Setting size in half-points (20 half-points = 10 points)
end
docx.h1 'Operator List Report'
docx.h3 "Generated on #{Time.now.strftime('%Y-%m-%d')}"
# Add Operator List with address in three columns
addresses.each_slice(3) do |row|
docx.table([row]) do
row.each do |address|
address.split(" /n ").each do |line|
docx.p line, font: 'Tahoma', size: 18, align: :left
end
end
end
end
end
# Send the file to the user
send_file 'report.docx', type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename: 'report.docx'
rescue => e
flash[:error] = "There was an error generating the document: #{e.message}"
redirect_to request.referrer
end
结束
好消息,SQL 可以运行并生成 docx。但是,我一生都无法将字符串/记录分割到我想要的位置,并且我最终会在单个表格单元格中使用多个运算符或自定义分隔符字符串来显示文字。
带分隔符的SQL select可供参考:
INSERT INTO #operatorTable (FormattedAddress)
SELECT DISTINCT
CONCAT_WS(' /n ',
CONCAT(rc.CONAME, ' (', rc.CONO, ')'),
NULLIF(rc.ADDR1, ''),
NULLIF(rc.ADDR2, ''),
RTRIM(CONCAT(
NULLIF(rc.CITY, ''),
CASE
WHEN rc.CITY <> '' AND rc.STATE <> '' THEN ', ' ELSE ''
END,
NULLIF(rc.STATE, ''),
' ',
CASE
WHEN NULLIF(rc.ZIP2, '') IS NOT NULL THEN CONCAT(NULLIF(rc.ZIP1, ''), '-', NULLIF(rc.ZIP2, ''))
ELSE NULLIF(rc.ZIP1, '')
END
)),
' | '
)
docx.table([row])
使用提供的原始字符串生成表格中的行,这就是您在表格单元格中看到新换行符的原因。
docx.p
正在将值打印到文档中,这就是换行符正确但位于表格之外的原因。
看来您想做的是使用
Caracal::Core::Models::TableCellModel
。如文档中所述:
如果您的表格包含更复杂的数据(多个段落、图像、列表等),您可能需要直接实例化 TableCellModel 实例
请尝试这个:(未经测试)
Caracal::Document.save 'report.docx' do |docx|
docx.style do
id 'Normal'
name 'Tahoma'
font 'Tahoma'
size 20 # Setting size in half-points (20 half-points = 10 points)
end
docx.h1 'Operator List Report'
docx.h3 "Generated on #{Time.now.strftime('%Y-%m-%d')}"
# construct all the cells first
cells = addresses.each do |address|
Caracal::Core::Models::TableCellModel.new do
address.each_line(chomp: true) do |line|
p line.strip
end
end
end
# add all the rows to the table at once
docx.table([cells.each_slice(3).to_a])
end