在实际工作中不可避免的会遇上统计、导出报表的工作,我自己整理了一份导出Excel代码放到这里,即为了分享知识,也是对自己的总结
首先导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
poi依赖是用来操作Excel的依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
poi-ooxml是poi的升级版
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
poi-ooxml-schemas可以支持office2007文件, 一般的Excel操作有这三个就够用了
生成之后可以使用浏览器下载Excel的方式,也可以保存到本地,返回到浏览器要用到HttpServletResponse ,保存到本地则不用。
导出Excel代码:
//第一步,创建一个HSSFWorkbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,为工作簿创建一个新工作表,传入表名
HSSFSheet sheet = wb.createSheet("测试");
// 第三步,在sheet中添加表头第0行
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格样式,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 创建一个居中格式
//第五步创建字体样式
Font headerFont = wb.createFont();//创建一个字体
headerFont.setFontName("Arial");//设置字体的名称(如Arial)
headerFont.setFontHeightInPoints((short) 12);//设置字体高度
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);//设置字体加粗
headerFont.setColor(HSSFColor.BLACK.index);//设置字体的颜色
style.setFont(headerFont);//应用该字体
//创建一个合并的单元格对象
sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));//创建合并的单元格范围
//在行中创建新的单元格并返回
HSSFCell cell = row.createCell(0);
cell.setCellValue("导出表单测试");//添加标题
cell.setCellStyle(style);//将样式赋值
//写入execl列标题
//创建标题行
row = sheet.createRow(1);
//标题数据
String[] title = {"测试列1","测试列2","测试列3"};
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 20 * 256);
}
//创建内容
String[] [] values = {{"11","12","13"},{"21","22","23"},{"31","32","33"}};
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 2);//创建数据行
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
生成Excel完毕
下面是发送回浏览器,需要指定响应头
//发送回浏览器
try (OutputStream os = response.getOutputStream();){//从response中获取输出流
String fileName = new String("测试导出Excel.xls".getBytes(), "ISO8859-1");//准备好文件名
response.setContentType("application/octet-stream;charset=ISO8859-1");//返回类型
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
wb.write(os);//写出到浏览器
os.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
这样导出Excel到浏览器就完成了
下面是保存到本地
try {
File file = new File("D://upFiles/" + "files/");
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String savePath = file.getPath() +"/test.xls";
OutputStream os = new FileOutputStream(savePath);
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}