程序只有一個頁面,點擊下載連接,下載Excel文檔,該文檔有兩個sheet,這兩個sheet和裏面的內容是使用JExcelApi生成的。html
增長一個下載頁面的controller和viewgit
SampleExcelController .groovygithub
<!-- lang: groovy --> package com.tutorial class SampleExcelController { def index() { } }
index.gspapi
<!-- lang: groovy --> <!DOCTYPE html> <html> <head> <meta name="layout" content="main"/> <title>Simple Chat</title> </head> <body> <g:link action="downloadSampleExcel">Download Sample Excel</g:link> </body> </html>
在config/BuildConfig.groovy中引入jexcelapi的包文件瀏覽器
<!-- lang: groovy --> dependencies { runtime 'net.sourceforge.jexcelapi:jxl:2.6.12' }
下面的代碼用來生成Excel文檔並提供下載服務器
<!-- lang: groovy --> package com.tutorial import jxl.Workbook import jxl.write.Label import jxl.write.WritableSheet import jxl.write.WritableWorkbook class SampleExcelController { def index() { } def downloadSampleExcel() { response.setContentType('application/vnd.ms-excel') response.setHeader('Content-Disposition', 'Attachment;Filename="example.xls"') WritableWorkbook workbook = Workbook.createWorkbook(response.outputStream) WritableSheet sheet1 = workbook.createSheet("Students", 0) sheet1.addCell(new Label(0,0, "First Name")) sheet1.addCell(new Label(1,0, "Last Name")) sheet1.addCell(new Label(2,0, "Age")) sheet1.addCell(new Label(0,1, "John")) sheet1.addCell(new Label(1,1, "Doe")) sheet1.addCell(new Label(2,1, "20")) sheet1.addCell(new Label(0,2, "Jane")) sheet1.addCell(new Label(1,2, "Smith")) sheet1.addCell(new Label(2,2, "18")) WritableSheet sheet2 = workbook.createSheet("Courses", 1) sheet2.addCell(new Label(0,0, "Course Name")) sheet2.addCell(new Label(1,0, "Number of units")) sheet2.addCell(new Label(0,1, "Algebra")) sheet2.addCell(new Label(1,1, "3")) sheet2.addCell(new Label(0,2, "English Grammar")) sheet2.addCell(new Label(1,2, "5")) workbook.write(); workbook.close(); } }
1.下面的代碼告訴瀏覽器,須要下載的文檔類型以及文件名app
<!-- lang: groovy --> response.setContentType('application/vnd.ms-excel') response.setHeader('Content-Disposition', 'Attachment;Filename="example.xls"')
2.WritableWorkbook用來建立一個Excel文檔實例,經過response.outputStream響應告訴咱們,這個文檔不是保存到服務器端,而是直接發送給瀏覽器ui
3.WritableSheet的第二個參數是sheet的索引,0表明第一個插件
4.addCell中第一和第二個參數則是Excel表格中的座標值excel
上面的代碼只是簡單介紹不使用插件怎麼生成Excel文檔,你能夠根據本身的項目須要修改使用。這裏是完整的代碼下載地址