POI下载excel
Posted z_java_20150812
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POI下载excel相关的知识,希望对你有一定的参考价值。
后台代码:
/**
* 下载汇总
* @param request
* @param map
* @return
*/
@RequestMapping(value = "excel")
public String excel(HttpServletRequest request, HttpServletResponse response, ModelMap map)
String template_id = CmnUtFunc.nvl(request.getParameter("template_id"));
DataCenterTemplate dataCenterTemplate = companyDataManageService.getTemplateById(template_id);
String path = dataCenterTemplate.getTemplatePath(); // 模板文件在服务器端的存放路径
File file = new File(path);
Map<String, List<String>> oriSheetMap = ExcelUtil.getExcelInfo(file);
List<Map<Integer, List<Integer>>> gatherList = ExcelUtil.getGatherInfo(file);
List<List<Map>> exportList = new ArrayList<List<Map>>();
for(Entry<String, List<String>> entry : oriSheetMap.entrySet())
String sheet_name = entry.getKey();
List<Map> sheetList = dataReportUploadService.getGatherList(template_id, sheet_name);
exportList.add(sheetList);
this.exportData(gatherList, exportList, file, request, response);
return "dataReport/toExcel.jsp";
/**
* 数据导出
*/
private void exportData(List<Map<Integer, List<Integer>>> gatherList, List<List<Map>> exportList, File file, HttpServletRequest request, HttpServletResponse response)
String template_id = CmnUtFunc.nvl(request.getParameter("template_id"));
DataCenterTemplate dataCenterTemplate = companyDataManageService.getTemplateById(template_id);
String template_name = dataCenterTemplate.getTemplateName();
Workbook workbook = null;
Sheet sheet=null;
try
//创建对象
String strExcelName = file.getAbsolutePath();
String fileType = String.valueOf(strExcelName.substring(strExcelName.lastIndexOf(".") + 1));
if ("xls".equals(fileType))
workbook = new HSSFWorkbook(new FileInputStream(file));
else if ("xlsx".equals(fileType))
workbook = new XSSFWorkbook(new FileInputStream(file));
for (int i = 0, index2 = 0; i < workbook.getNumberOfSheets(); i++) //获取每个Sheet表
sheet = workbook.getSheetAt(i);
String sheet_name = sheet.getSheetName();
if (sheet_name.indexOf(DataReportConstance.SHEET_NO_READ) >= 0)
continue;
if (sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 0)
continue;
List<Map> sheetList = exportList.get(index2); // 导出数据
/**
* 有合计行:删掉标题行和合计行之间的行,从标题行开始插入行写数据,设置求和公式
* 无合计行:删掉标题行之后的行,从标题行+1开始写数据
*/
boolean flag = false;
int begin_index = ExcelUtil.X;
int endRow = 0;
List<Integer> tList = new ArrayList<Integer>();
for (Entry<Integer, List<Integer>> entry : gatherList.get(index2).entrySet())
endRow = entry.getKey();
tList = entry.getValue();
if (tList.size() > 0)
flag = true;
Row titleRow = sheet.getRow(ExcelUtil.X-1);
int col_count = titleRow.getPhysicalNumberOfCells();
// 使用模板文件中单元格的样式
List<CellStyle> stList = new ArrayList<CellStyle>();
Row stRow = sheet.getRow(begin_index);
if (stRow != null)
for (int k = ExcelUtil.Y-1; k < col_count+(ExcelUtil.Y-1); k++)
if (stRow.getCell(k) != null)
stList.add(stRow.getCell(k).getCellStyle());
else
stList.add(null);
for (int j = 0; j < sheetList.size(); j++)
Map<String, String> map = sheetList.get(j);
sheet.shiftRows(begin_index, sheet.getLastRowNum(),1,true,false); // begin_index到 sheet.getLastRowNum()行,下移
Row row = sheet.createRow(begin_index);
if (stRow != null)
row.setHeight(stRow.getHeight()); // 设置行高
int index = 1;
for (int k = ExcelUtil.Y-1; k < col_count+(ExcelUtil.Y-1); k++)
Cell cell = row.createCell(k);
if (flag && tList.contains(k))
cell.setCellValue(Double.parseDouble(map.get("DATE_A"+index) == null ? "0" : map.get("DATE_A"+index)));
else
cell.setCellValue(map.get("DATE_A"+index));
if (stRow != null && stList.size() > index-1 &&stList.get(index-1) != null)
cell.setCellStyle(stList.get(index-1));
index++;
begin_index++;
for (int j = ExcelUtil.X+1; j < endRow+1; j++)
sheet.shiftRows(ExcelUtil.X+1+sheetList.size(), sheet.getLastRowNum()+1, -1,true,false); // 删除模板文件中的示例数据行 ,示例数据行下方,整行上移
if (flag)
Row totalRow = sheet.getRow(ExcelUtil.X + sheetList.size());
for (int j = 0; j < tList.size(); j++)
String colString = CellReference.convertNumToColString(tList.get(j)); //长度转成ABC列
String sumstring = "SUM(" + colString + (ExcelUtil.X +1) + ":" + colString + (sheetList.size()+ ExcelUtil.X) + ")"; // 求和公式
totalRow.getCell(tList.get(j)).setCellFormula(sumstring);
index2++;
String filePath = DataReportConstance.B2B_DATAREPORT_EXPORT_PATH;
String fileName = template_name + "汇总" + "." + fileType;
File filepath = new File(filePath);
if (!filepath.exists())
filepath.mkdirs();
request.setAttribute("filePath",filePath);
request.setAttribute("fileName",fileName);
FileOutputStream fileOut = new FileOutputStream(filePath+fileName);
workbook.write(fileOut);
fileOut.close();
catch (Exception e)
// TODO: handle exception
e.printStackTrace();
前台代码:
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/common/lib/taglibs.jsp"%>
<%@ page import="java.io.*" %>
<%
String fileName = (String)request.getAttribute("fileName");
String filePath = (String)request.getAttribute("filePath");
FileInputStream inStream=new FileInputStream(filePath + fileName);
String realFileName = CmnUtFunc.nvl(request.getAttribute("realFileName"));
if(!"".equals(realFileName))
fileName = realFileName;
//设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition","attachment; filename=\\"" + URLEncoder.encode(fileName, "UTF-8") + "\\"");
response.setHeader("Content-Length", String.valueOf(inStream.getChannel().size())); // 如果没有此行代码,打开excel文件时,会提示“发现不可读取的内容,是否继续”
//循环取出流中的数据
byte[] b = new byte[1024];
int len;
while((len=inStream.read(b)) >0)
response.getOutputStream().write(b,0,len);
inStream.close();
%>
以上是关于POI下载excel的主要内容,如果未能解决你的问题,请参考以下文章