版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhouchenxuan/article/details/78943967
今天给大家带来javaweb项目使用poi导出excel的入门示例,适用于初次接触的新手。导出excel分两步:1、生成一个excel放在工作目录下,2、把它导出到本地。
请读者自行下载所需jar包,如图:
然后将jar包引入
接下来放代码。代码看起来复杂,其实稍微一分析,so easy!!!
jsp页面
//第一步,生成excel放在一个目录里
//给页面上一个按钮添加点击事件
$('#exportBtn').bind('click', function() {
$.ajax({
async : true,
cache : false,
type : 'post',
dataType : 'json',
data : {},
//url需要自己修改
url : '${ctx}/convert/createExcel',
//第二步,把目录里的文件导出到本地
success : function(result) {
if($('#download').length > 0) {
//这里的url也需要自己修改
$('#download').attr('src', '${ctx}/convert/down?fileNm=' + result.fileNm);
} else {
$('body').append($('<iframe id="download" style="display : none" />'));
$('#download').attr('src', '${ctx}/convert/down?fileNm=' + result.fileNm);
}
}
});
});
java代码(生成excel):
@RequestMapping("/createExcel")
@ResponseBody
public Map<String, Object> createExcel() throws IOException {
//先来造点数据
//假设有3列,分别为编号、姓名、年龄
Map<String, Object> titles = new LinkedHashMap<String, Object>();
titles.put("id", "编号");
titles.put("name", "姓名");
titles.put("age", "年龄");
//自己编3行数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map1.put("id", "001");
map1.put("name", "张三");
map1.put("age", "29");
list.add(map1);
map2.put("id", "002");
map2.put("name", "李四");
map2.put("age", "26");
list.add(map2);
map3.put("id", "003");
map3.put("name", "王五");
map3.put("age", "25");
list.add(map3);
//生成excel正式开始
//导出excel最基本对象
HSSFWorkbook book = new HSSFWorkbook();
//sheet页对象
HSSFSheet sheet = (HSSFSheet)book.createSheet("sheet页名称");
//单元格格式对象
HSSFCellStyle style = book.createCellStyle();
//设置一下上下左右的格式
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
int rowNum = 0;//行序号,从第0行开始
int colNum = 0;//列序号,从第0行开始
//行对象,代指某一行
Row row = sheet.createRow(rowNum);
//单元格对象
Cell cell = null;
for(String key : titles.keySet()) {
//创建一个单元格
cell = row.createCell(colNum);
//给单元格写数据
cell.setCellValue(titles.get(key).toString());
//设置一下风格
cell.setCellStyle(style);
//设置行高
row.setHeightInPoints(20);
//换到下一个单元格(同一行的下一列)
colNum++;
}
//换行
rowNum++;
//回到第0列
colNum = 0;
//写数据,同写标题,同上
for(int i = 0;i < list.size();i++) {
Map<String, Object> data = list.get(i);
row = sheet.createRow(rowNum);
for(String key : titles.keySet()) {
cell = row.createCell(colNum);
cell.setCellValue(data.get(key).toString());
cell.setCellStyle(style);
row.setHeightInPoints(20);
//设置一下列宽
sheet.setColumnWidth(colNum, data.get(key).toString().getBytes().length * 2 * 256);
colNum++;
}
rowNum++;
colNum=0;
}
//生成文件
Map<String, Object> result = new HashMap<String, Object>();
//注意转义,或者用File.separator
//必须找一个web下的某一个路径,不然报错
String fileNm = "C:\\study\\eclipse\\workspace\\spring_poi\\WebContent\\1.xlsx";
result.put("fileNm", fileNm);
OutputStream out = new FileOutputStream(fileNm);
book.write(out);
return result;
}
java代码(下载excel):
//单纯的文件下载,读者也可以自己写一个
@RequestMapping("/down")
public void down(HttpServletResponse response, String fileNm) throws IOException {
File file = new File(fileNm);
String finalNm = "final.xlsx";
response.setContentType("text/html;charset=UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
long fileLength = file.length();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(finalNm.getBytes("gbk"), "ISO8859-1") );
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
然后是测试效果
(好土。。。)
点击“导出”。。。
就可以下载excel了。
还是很土。。。