程序只有一个页面,点击下载链接,下载Excel文档,该文档有两个sheet,这两个sheet和里面的内容是使用JExcelApi生成的。
增加一个下载页面的controller和view
SampleExcelController .groovy
package com.tutorial
class SampleExcelController {
def index() { }
}
index.gsp
<!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的包文件
dependencies {
runtime 'net.sourceforge.jexcelapi:jxl:2.6.12'
}
下面的代码用来生成Excel文档并提供下载
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.下面的代码告诉浏览器,需要下载的文档类型以及文件名
response.setContentType('application/vnd.ms-excel')
response.setHeader('Content-Disposition', 'Attachment;Filename="example.xls"')
2.WritableWorkbook用来创建一个Excel文档实例,通过response.outputStream响应告诉我们,这个文档不是保存到服务器端,而是直接发送给浏览器
3.WritableSheet的第二个参数是sheet的索引,0代表第一个
4.addCell中第一和第二个参数则是Excel表格中的坐标值
上面的代码只是简单介绍不使用插件怎么生成Excel文档,你可以根据自己的项目需要修改使用。这里是完整的代码下载地址