版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/samile6899/article/details/54093456
在一般JAVA开发的后台管理系统中,都会有用到导出EXCEL的这个功能。但是一般后台系统可能用着用着,数据量就会变的越来越大,可能以前刚开始用的时候数据库中数据不多,只有500条,那么一年甚至两年后可能系统后台的数据会达到20万~40万的数据甚至更多,那么这个时候导出 excel 的时候,代码就会显得特别重要,那么这个时候就要开始考虑到代码的优化及使用了。废话不多说,直接上代码!
public String exportFrozenFunds(Map<String, String> param, HttpServletRequest request){
Map searchmap = new HashMap();
String _key_searchInstitutions_keyId = StringUtil.safeToString(param.get("_key_searchInstitutions_keyId"), ""); //股票代码输入的内容
String stkcode = StringUtil.safeToString(param.get("_key_securitycode"), "");
if (StringUtil.isNotBlank(_key_searchInstitutions_keyId) && StringUtil.isNotBlank(stkcode))
searchmap.put("stkcode", stkcode);
String _key2_searchInstitutions_keyId = StringUtil.safeToString(param.get("_key2_searchInstitutions_keyId"), "");
String fundname = StringUtil.safeToString(param.get("_key2_searchInstitutions"), "");
if (StringUtil.isNotBlank(_key2_searchInstitutions_keyId) && StringUtil.isNotBlank(fundname))
searchmap.put("fundname", fundname);
List<Map> dataList = OvercounterServiceFactory.getOvercounterInquiryService().searchFrozenList(searchmap).getResult();
try {
String _filePath = request.getSession().getServletContext().getRealPath("temp") + File.separator;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String _fileName = "导出EXCEL_" + dateFormat.format(new Date());
Map exportFileInfoMap = new HashMap();
String fileSuffix = "xls";
exportFileInfoMap.put("fileName", _fileName);
exportFileInfoMap.put("fileSuffix", fileSuffix);
String[][] colInfoArray=null;
colInfoArray = new String[][]{{
{"字段名0", "字段名1", "字段名2", "字段名3", "字段名4", "字段名5", "字段名6", "字段名7", "字段名8","字段名9","字段名10"},
{"dataList中的字段0定义的name", "字段1定义的name", "字段2定义的name", "字段3定义的name", "字段4定义的name", "字段5定义的name", "字段6定义的name", "字段7定义的name", "字段8定义的name","字段9定义的name","字段10定义的name"},
{"8000","8000", "8000", "8000", "8000", "8000", "8000", "8000", "8000","8000", "8000"} //excel的长度设置
};
exportFileInfoMap.put("colInfoArray", colInfoArray);
//导出EXCEL文档
String path = null;
try {
path = ExcelUtils.exportExcel(dataList, exportFileInfoMap);
} catch (IOException e) {
e.printStackTrace();
}
String a = "/downloads/download.jsp?path=" + path + "&name=" + _fileName + "." + fileSuffix+"&name=" + _fileName;
LOGGER.info(a);
return a;
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
public static String exportExcel(List<Map> list, Map exportFileInfoMap) throws IOException {
String exportPath = "";
String fileName = exportFileInfoMap.get("fileName").toString();
String fileSuffix = exportFileInfoMap.get("fileSuffix").toString();
int version = 0;
if (fileSuffix.equals("xls"))
version = office2003;
else if (fileSuffix.equals("xlsx")) {
version = office2007;
} else {
LOGGER.error("非指定格式的导出文件!");
throw new FileNotFoundException();
}
LOGGER.info("--- "+fileName+"开始导出... ---");
// 创建临时文件
String _tempDir = SettingUtils.getStringValue("COMMON", "TEMPDIR");
int count = 2;
String _prefix = _tempDir + File.separatorChar + fileName + TimeUtil.formatDate(new Date(), "yyyyMMddHHmmss");
exportPath = _prefix + "." + fileSuffix;
File _file = new File(exportPath);
while(_file.exists()){
exportPath = _prefix + "_" + count + "." + fileSuffix;
_file = new File(exportPath);
count++;
}
try{
_file.createNewFile();
}
catch(Exception ex){
_file = null;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (CollectionUtils.isEmpty(list)) {
LOGGER.error("未获取到可导出数据!");
return "";
} else {
LOGGER.info("将导出[" + list.size() + "]个数据");
String[][] colInfoArray = (String[][]) exportFileInfoMap.get("colInfoArray");
exportfile(_file, list, colInfoArray, version, fileName);
LOGGER.info("共导出[" + list.size() + "]个数据!导出路径为:" + exportPath);
return exportPath;
}
}
private static void exportfile(File file, List colDataList, String[][] colInfoArray, int version, String sheetName) {
String[] colTitleArray = colInfoArray[0];
String[] colPropertyArray = colInfoArray[1];
String[] colWidthArray = colInfoArray[2];
int colNum = colTitleArray.length;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (version == office2003) {
HSSFWorkbook wb = new HSSFWorkbook();
int rowNum = colDataList.size();
int sheetNum = rowNum%MAXSHEETNUM==0 ? rowNum/MAXSHEETNUM : rowNum/MAXSHEETNUM + 1;
sheetNum = rowNum == 0 ? 1 : sheetNum;
for (int k = 0; k < sheetNum; k++) {
int currSheetRowNumMax = (k == sheetNum - 1) ? rowNum%MAXSHEETNUM : MAXSHEETNUM;
int rowIdIntial = k * MAXSHEETNUM;
HSSFSheet sheet = wb.createSheet(sheetName + "信息(分页" + (k+1) + ")");
HSSFRow head = sheet.createRow(0);
HSSFCellStyle cellstyle = wb.createCellStyle();
cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置水平对齐方式
cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //设置垂直对齐方式
HSSFFont font = wb.createFont();
for (int j=0; j<colNum; j++) {
createCell(head, j, colTitleArray[j], 0, cellstyle, font);
sheet.setColumnWidth(j, NumberTool.safeToInteger(colWidthArray[j], 8000));
}
HSSFRow row_context = null;
for (int i = 0; i < currSheetRowNumMax; i++) {
Map map = (Map) colDataList.get(i + rowIdIntial);
row_context = sheet.createRow(i + 1);
for (int j = 0; j < colNum; j++) {
if(colPropertyArray[j].equals("frozenmoney2")){
createCell(row_context, j, formatMoney(map.get(colPropertyArray[j]).toString(),2), 1, cellstyle, font);
}else{
createCell(row_context, j, StringUtil.safeToString(map.get(colPropertyArray[j]), colPropertyArray[j]), 1, cellstyle, font);
}
}
}
}
wb.write(fos);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
}
}
}
public static void createCell(HSSFRow row, int col, String val, int type, HSSFCellStyle cellstyle, HSSFFont font) {
HSSFCell cell = row.createCell(col);
cell.setCellValue(val);
//设置单元格样式
if (0 == type) {
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);//设置字体大小
cellstyle.setFont(font);
} else {
font.setFontName("宋体");
font.setFontHeightInPoints((short) 10);//设置字体大小
cellstyle.setFont(font);
}
//设置单元格格式
//cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellStyle(cellstyle);
}
/**
* 格式化金额
* @param s
* @param len
* @return
*/
public static String formatMoney(String s, int len)
{
if (s == null || s.length() < 1) {
return "";
}
java.text.NumberFormat formater = null;
double num = Double.parseDouble(s);
if (len == 0) {
formater = new DecimalFormat("###,###");
} else {
StringBuffer buff = new StringBuffer();
buff.append("###,###.");
for (int i = 0; i < len; i++) {
buff.append("#");
}
formater = new DecimalFormat(buff.toString());
}
String result = formater.format(num);
if(result.indexOf(".") == -1)
{
result = result + ".00";
}
else
{
result = result;
}
return result;
}
之后返回JSP页面,会返回这样的一串字符串:“
String a = "/downloads/download.jsp?path=" + path + "&name=" + _fileName + "." + fileSuffix+"&name=" + _fileName;
function exportFrozenFund() {
stk.confirm("确定导出该名单信息?",function(){
$("#searchform").stk_submit("exportFrozenFunds",function(result){
if(result != ""){
window.location.href = sirm.jsurl(result);
}
});
})
}
会进入一个download.jsp,在这个download.jsp中会自动下载excel文档。这样的话就实现了导出的功能,速度也会有所加强。
<%
String paths = request.getParameter("path");
String path = new String(paths.getBytes("ISO-8859-1"),"UTF-8");
if (!StringUtil.isStrTrimEmpty(path)) {
String names = request.getParameter("name");
String name = new String(names.getBytes("ISO-8859-1"),"UTF-8");
BASE64Decoder decode = new BASE64Decoder();
// String realPath =new String(decode.decodeBuffer(URLDecoder.decode(path,"UTF-8")));
String realPath=path;
File file = new File(realPath);
try{
if (file.exists()) {
String disposition = "attachment;filename=" + URLEncoder.encode(name,"UTF-8");
response.setContentType("application/x-msdownload;charset=UTF-8");//注意(2)
response.setHeader("Content-disposition", disposition);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
int len = 0;
OutputStream output=response.getOutputStream();
while ((len = fis.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
output.flush();
output.close();
}
}catch (Exception ex){
String simplename = ex.getClass().getSimpleName();
if(!"ClientAbortException".equals(simplename)){
ex.printStackTrace();
}
}
}
%>