核心思路:
1.視圖:給spring提供excel視圖支援
2.資料:查詢業務資料
3.載體:poi元件建構表格樣式
1.給項目增加excel支援,項目中導入poi-*.jar等操作excel檔案的jar檔案(我使用的是poi3.8版本的)
poi-3.8-20120326.jar
poi-excelant-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
2.擴充AbstractExcelView抽象類,實作自己的excel類,需要實作buildExcelDocument方法,我實作的類是com.ttpod.stusys.common.excel.ExcelRevenueReportView,主要代碼如下:
List<Log> logList = (List<Log>) logList;//從控制器Controller中傳回的業務資料
HSSFSheet sheet = workbook.createSheet("tableTitle"); //建立表格
HSSFRow header = sheet.createRow(0);//定義表格的表頭
header.createCell(0).setCellValue(cellTitle);//建立表頭列
HSSFRow row = sheet.createRow(rowNum); //建立表格行
row.createCell(0).setCellValue(從logList中解析的資料); //建立單元格并且給其指派
3.在spring-servlet.xml中配置excel視圖,代碼片段如下:
No1.
<!-- 對模型視圖名稱的解析,在模型視圖名稱添加前字尾 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp">
<!-- 此配置優先級要最高 -->
<property name="order" value="1" />
</bean>
No2.
<!-- 從一個獨立的xml配置檔案中引用excel視圖展示類(當然也可以直接在spring-servlet.xml檔案中定義excel視圖展示類) -->
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<!-- 此視圖在src目錄下 -->
<value>classpath:spring-excel-views.xml</value>
</property>
<property name="order" value="10" />
</bean>
No3.
<!-- 定義excel視圖展示類(引用上面第二步驟實作的excel類) -->
<bean id="view_excel"
class="com.ttpod.stusys.common.excel.ExcelRevenueReportView">
</bean>
No.4
也可以不建立spring-excel-views.xml檔案,直接在spring-servlet.xml檔案中定義如下内容:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="10"/>
<bean id="view_excel"
class="com.ttpod.stusys.common.excel.ExcelRevenueReportView">
</bean>
4.在控制器Controller中傳回excel格式的視圖,代碼片段如下:
@Controller
@RequestMapping("/view/")
public class ExportController{
/**
* 展示excel視圖的方法
/
@RequestMapping("/excel")
protected ModelAndView excel(...){
String filename = new String("中文檔案名稱".getBytes(),"iso8859-1");
response.setHeader("Content-Disposition","attachment;filename="+filename+".xls");
List<Log> logList = 調用業務層查詢日志資料
//view_excel是在spring配置檔案裡配置的ExcelRevenueReportView,第二個和第三個參數采用鍵值對方法提供給buildExcelDocument方法使用
return new ModelAndView("view_excel","logList",logList);
}
}
5.打開浏覽器通路,會以下載下傳檔案的方式下載下傳excel資料
http://127.0.0.1:8080/項目部署名稱/view/excel.do