2010年12月22日,冬至。 今天终于把南美话单分拣报表做完,主要实现将报表数据用EXCEL导出。于是自己写了一个小例子与大家分享。
1、准备Apache提供的开源jar包poi-3.0.1-FINAL-20070705.jar,我将把它上载上来,供大家方便使用。
2、编写导出Excel类
package com.zte.excel;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelReport {
public void export(HttpServletResponse response) throws IOException {
response.setHeader("Content-disposition", "attachment;filename=test.xls");
OutputStream out = response.getOutputStream();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");
//模拟数据
String[] head = {"第一列","第二列","第三列","第四列"};
Object[][] body = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{"我","爱","你","!"}};
//文件头
HSSFRow rowHead = sheet.createRow(0);
for(int i = 0; i< head.length; i++) {
HSSFCell cell = rowHead.createCell((short)i);
cell.setCellValue(new HSSFRichTextString(head[i]));
}
//文件体
for(int j = 0; j < body.length ; j ++) {
for(int k = 0 ; k < body[j].length ; k++ ) {
HSSFRow rowBody = sheet.createRow(j + 1);
HSSFCell cell = rowBody.createCell((short)k);
cell.setCellValue(new HSSFRichTextString(String.valueOf((body[j][k]))));
}
}
wb.write(out);
}
}
3、编写Servlet
package com.zte.excel;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class for Servlet: ExcelControl
*
*/
public class ExcelControl extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ExcelReport excelReport = new ExcelReport();
excelReport.export(response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
4、编写index.htm页面
<html>
<head>
<script type="text/javascript">
function exportExcel(){
window.location="ExcelControl"
}
</script>
</head>
<body>
<center>
<div style="border:1px red solid;width:250;height: 100;background-color:yellow;">
<br>
<h3><---Excel表导出测试---></h3>
<input type="button" value="导出EXCEL" onclick="exportExcel()" />
</div>
</center>
</body>
</html>
5、 启动Tomcat,并访问页面index.html页面
OK,成功