Excel

package com.e6soft.project.ExcelUtil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import com.e6soft.base.annotations.JCall;
import com.e6soft.base.util.DateUtil;
import com.e6soft.base.util.StringUtil;
import com.e6soft.base.util.SysUtil;
import com.e6soft.base.util.WebUtil;

/**
 * Excel 工具类
 * 
 * @author Administrator
 * 
 */
public class ExcelUtil3 {
    //excel模板路径
    private static final String baseExcelModelUrl = System.getProperty("catalina.home") + "/webapps/pmp_v1/excelModel/";
    
    //模版位置
    private static final String excelModelName1 = "moban1.xls";
    //
    private static final String excelModelName2 = "moban2.xls";
// private static final String excelModelName3 = "moban3.xls";
// private static final String excelModelName4 = "moban4.xls";
// private static final String excelModelName5 = "moban5.xls";
// private static final String excelModelName6 = "moban6.xls";
// private static final String excelModelName7 = "moban7.xls";
// private static final String excelModelName8 = "moban8.xls";
/** * 导入excel模板 * * @throws FileNotFoundException * @throws IOException */ private static HSSFWorkbook importExcellModel(String excelurl) throws FileNotFoundException, IOException { File file = new File(excelurl); if (!file.isFile()) { file = new File(excelurl.replace("pmp_v1", "fsxc3")); } InputStream is = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(is); return wb; } /** * 替换表格${}数据 * * @param replaceDataMap * @param sheet */ private static void replaceCellValue(Map<String, Object> replaceDataMap,HSSFSheet sheet) { Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); if (row != null) { int num = row.getLastCellNum(); if (row.getRowNum() > 3) { break; } for (int i = 0; i < num; i++) { HSSFCell cell = row.getCell(i); if (cell == null || cell.getStringCellValue() == null) { continue; } String cellValue = cell.getStringCellValue(); if (!"".equals(cellValue)) { if (cellValue.indexOf('$') != -1) { cell.setCellValue(getReplaceValue(cellValue, replaceDataMap)); } } else { cell.setCellValue(""); } } } } } /** * 获取替换${}对应的数据 */ private static String getReplaceValue(String cellValue, Map<String, Object> replaceDataMap) { // 获取$出现的次数。 int num = 0; for (int i = 0; i < cellValue.length(); i++) { if ("$".equals(cellValue.substring(i, i + 1))) { num++; } } for (int i = 0; i < num; i++) { String str = cellValue.substring(cellValue.indexOf('{') + 1, cellValue.indexOf('}')); if (null == replaceDataMap.get(str)) { cellValue = cellValue.replace("${" + str + "}", ""); } else { cellValue = cellValue.replace("${" + str + "}", (String) replaceDataMap.get(str)); } } return cellValue; } /** * 复制Excel并插入数据 * @param modelName * @param dataArray * @param fieldName * @throws FileNotFoundException * @throws IOException */ public static HSSFWorkbook createHSSFSheet(String modelName,List<Map<String,Object>> dataArray,String[] fieldName) throws FileNotFoundException, IOException{ HSSFWorkbook wb; HSSFSheet sheet; HSSFCell cell; if("moban1".equals(modelName)){//模版名称 wb = importExcellModel(baseExcelModelUrl+excelModelName1); }else if("moban2".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName2); }else if("moban3".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName3); }else if("moban4".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName4); }else if("moban5".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName5); }else if("moban6".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName6); }else if("moban7".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName7); }else if("moban8".equals(modelName)){
wb = importExcellModel(baseExcelModelUrl+excelModelName8); }else{ return null; } sheet = wb.getSheetAt(0); //设置建表时间数据 Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int mouth = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); Map<String, Object> replaceDataMap = new HashMap<String, Object>(); replaceDataMap.put("year", String.valueOf(year)); replaceDataMap.put("mouth", String.valueOf(mouth)); replaceDataMap.put("day",String.valueOf(day)); replaceCellValue(replaceDataMap, sheet); //导入数据 int rowNum = 3; sheet.shiftRows(rowNum+1, sheet.getPhysicalNumberOfRows(), dataArray.size()); HSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setWrapText(true); cellStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中 cellStyle.setBorderBottom((short) 1); cellStyle.setBorderLeft((short) 1); cellStyle.setBorderRight((short) 1); cellStyle.setBorderTop((short) 1); int colNum = -1; for (int i = 0; i < dataArray.size(); i++) { //数据 Map<String, Object> dataMap = dataArray.get(i); //创建行 HSSFRow row = sheet.createRow(++rowNum); //序号列 cell = row.createCell(++colNum); cell.setCellValue(i + 1); cell.setCellStyle(cellStyle); //数据列 for(int j=0;j<fieldName.length;j++){ cell = row.createCell(++colNum); cell.setCellValue(dataMap.get(fieldName[j].toLowerCase()).toString()); cell.setCellStyle(cellStyle); } colNum = -1; } return wb; } public static float getExcelCellAutoHeight(String str, float fontCountInline) { float defaultRowHeight = 12.00f;// 每一行的高度指定 float defaultCount = 0.00f; for (int i = 0; i < str.length(); i++) { float ff = getregex(str.substring(i, i + 1)); defaultCount = defaultCount + ff; } return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;// 计算 } public static float getregex(String charStr) { if (charStr == " ") { return 0.5f; } // 判断是否为字母或字符 if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) { return 0.5f; } // 判断是否为全角 if (Pattern.compile("[u4e00-u9fa5]+$").matcher(charStr).matches()) { return 1.00f; } // 全角符号 及中文 if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) { return 1.00f; } return 0.5f; } /** * 用HSSFWorkbook生成excel文件在服务器 * * @param excelName * @param wb * @throws FileNotFoundException * @throws IOException */ public static boolean generateExcel(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException { try { // 输出文件 String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls"; File fileOut = new File(writeExcelUrl); FileOutputStream os = new FileOutputStream(fileOut); wb.write(os); close(os); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); return false; } return true; } /** * 用HSSFWorkbook生成excel文件在服务器 * * @param excelName * @param wb * @throws FileNotFoundException * @throws IOException */ public static String generateExcel2(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException { String dz = ""; try { // 输出文件 String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls"; File fileOut = new File(writeExcelUrl); FileOutputStream os = new FileOutputStream(fileOut); wb.write(os); close(os); dz = fileName+".xls"; } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); return ""; } return dz; } /** * 用HSSFWorkbook生成excel文件给用户下载 * * @param excelName * @param wb * @throws IOException * @throws FileNotFoundException * @throws IOException */ public static boolean generateExcel(HttpServletResponse response,String fileName, HSSFWorkbook wb){ try { setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); close(os); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); return false; } return true; } /** * 关闭输出流 * @param os */ private static void close(OutputStream os) { if (os != null) { try { os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 发送响应流方法 * @param response * @param fileName */ public static void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String((fileName+".xls").getBytes("UTF-8"),"ISO8859-1"); //fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.reset(); response.setContentType("application/msexcel"); //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"); } catch (Exception ex) { ex.printStackTrace(); } } /** * xls打包成zip进行下载 */ public String downloads(String[] filepath, HttpServletResponse response,String name) throws IOException, ServletException { Date day = new Date(); SimpleDateFormat df = new SimpleDateFormat("HHmmss"); // 要生成的压缩文件地址和文件名称 String fileName = name + df.format(day) + ".zip"; String path = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName; File zipFile = new File(path); ZipOutputStream zipStream = null; FileInputStream zipSource = null; BufferedInputStream bufferStream = null; try { // 构造最终压缩包的输出流 zipStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (int i = 0; i < filepath.length; i++) { File file = new File(System.getProperty("catalina.home") + "/webapps/webdav/" + filepath[i]); // 将需要压缩的文件格式化为输入流 zipSource = new FileInputStream(file); // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样 ZipEntry zipEntry = new ZipEntry(file.getName()); // 定位该压缩条目位置,开始写入文件到压缩包中 zipStream.putNextEntry(zipEntry); // 输入缓冲流 bufferStream = new BufferedInputStream(zipSource, 1024 * 10); int read = 0; // 创建读写缓冲区 byte[] buf = new byte[1024 * 10]; while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) { zipStream.write(buf, 0, read); } } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭流 try { if (null != bufferStream) bufferStream.close(); if (null != zipStream) zipStream.close(); if (null != zipSource) zipSource.close(); } catch (IOException e) { e.printStackTrace(); } } return fileName; /* * //2.获取要下载的文件名 String fileName = * path.substring(path.lastIndexOf("\")+1); * //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 File fi=new File(path); * response.setHeader("Content-Disposition", * "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")); * response.addHeader("Content-Length", "" + fi.length()); * response.setContentType("application/octet-stream"); //4.获取要下载的文件输入流 * InputStream in = new FileInputStream(fi); int len = 0; //5.创建数据缓冲区 * byte[] buffer = new byte[1024]; //6.通过response对象获取OutputStream流 * OutputStream out = response.getOutputStream(); * //7.将FileInputStream流写入到buffer缓冲区 while ((len = in.read(buffer)) > 0) * { //8.使用OutputStream将缓冲区的数据输出到客户端浏览器 out.write(buffer,0,len); } * in.close(); */ } public static void main(String[] args) { /* 模板名 * bmlxhqdjb //部门立项会签登记表 * jhhybzbcgtz //计划合约部招标采购台账 * xckfgshttz //新城开发公司合同台账 * gczjzxwttz //工程造价咨询委托台账 * flgwgztz //法律顾问工作台账 * jhhybhtgztz //计划合约部合同工作台帐 * jhhybzbcgtz_xe //计划合约部招标采购台账-限额 * * 数据 * 需要导出的数据 * * 导出时列的属性名顺序 * 注意与数据的字段要对应 */ //HSSFWorkbook wb = createHSSFSheet(模板名,数据,导出时列的属性名顺序); /*try{ * if(generateExcel(response对象,导出文件的名字,wb)){ * //导出成功 * } *}catch (Exception e) { * //导出失败 *} */ } }

...

package com.e6soft.project.ExcelUtil;
import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import com.e6soft.base.annotations.JCall;import com.e6soft.base.util.DateUtil;import com.e6soft.base.util.StringUtil;import com.e6soft.base.util.SysUtil;import com.e6soft.base.util.WebUtil;
/** * Excel 工具类 *  * @author Administrator *  */public class ExcelUtil3 {//excel模板路径private static final String baseExcelModelUrl = System.getProperty("catalina.home") + "/webapps/pmp_v1/excelModel/";//部门立项会签登记表private static final String excelModelName1 = "fsxc_bmlxhqdjb_model.xls";//计划合约部招标采购台账private static final String excelModelName2 = "fsxc_jhhybzbcgtz_model.xls";//新城开发公司合同台账private static final String excelModelName3 = "fsxc_xckfgshttz_model.xls";//工程造价咨询委托台账private static final String excelModelName4 = "fsxc_gczjzxwttz_model.xls";//法律顾问工作台账private static final String excelModelName5 = "fsxc_flgwgztz_model.xls";//计划合约部合同工作台帐private static final String excelModelName6 = "fsxc_jhhybhtgztz_model.xls";//计划合约部招标采购台账-限额private static final String excelModelName7 = "fsxc_jhhybzbcgtz_xe_model.xls";//计划合约部招标采购台账-限额private static final String excelModelName8 = "fsxc_jhhyb_gc_model.xls";
/** * 导入excel模板 *  * @throws FileNotFoundException * @throws IOException */private static HSSFWorkbook importExcellModel(String excelurl) throws FileNotFoundException, IOException {File file = new File(excelurl);if (!file.isFile()) {file = new File(excelurl.replace("pmp_v1", "fsxc3"));}InputStream is = new FileInputStream(file);HSSFWorkbook wb = new HSSFWorkbook(is);return wb;}
/** * 替换表格${}数据 *  * @param replaceDataMap * @param sheet */private static void replaceCellValue(Map<String, Object> replaceDataMap,HSSFSheet sheet) {Iterator rows = sheet.rowIterator();while (rows.hasNext()) {HSSFRow row = (HSSFRow) rows.next();if (row != null) {int num = row.getLastCellNum();if (row.getRowNum() > 3) {break;}for (int i = 0; i < num; i++) {HSSFCell cell = row.getCell(i);if (cell == null || cell.getStringCellValue() == null) {continue;}String cellValue = cell.getStringCellValue();
if (!"".equals(cellValue)) {if (cellValue.indexOf('$') != -1) {cell.setCellValue(getReplaceValue(cellValue,replaceDataMap));}} else {cell.setCellValue("");}}}}}
/** * 获取替换${}对应的数据 */private static String getReplaceValue(String cellValue,Map<String, Object> replaceDataMap) {
// 获取$出现的次数。int num = 0;for (int i = 0; i < cellValue.length(); i++) {if ("$".equals(cellValue.substring(i, i + 1))) {num++;}}for (int i = 0; i < num; i++) {String str = cellValue.substring(cellValue.indexOf('{') + 1,cellValue.indexOf('}'));if (null == replaceDataMap.get(str)) {cellValue = cellValue.replace("${" + str + "}", "");} else {cellValue = cellValue.replace("${" + str + "}",(String) replaceDataMap.get(str));}}return cellValue;}
/** * 复制Excel并插入数据 * @param modelName * @param dataArray * @param fieldName * @throws FileNotFoundException * @throws IOException */public static HSSFWorkbook createHSSFSheet(String modelName,List<Map<String,Object>> dataArray,String[] fieldName) throws FileNotFoundException, IOException{HSSFWorkbook wb;HSSFSheet sheet;HSSFCell cell;if("bmlxhqdjb".equals(modelName)){//部门立项会签登记表wb = importExcellModel(baseExcelModelUrl+excelModelName1);}else if("jhhybzbcgtz".equals(modelName)){//计划合约部招标采购台账wb = importExcellModel(baseExcelModelUrl+excelModelName2);}else if("xckfgshttz".equals(modelName)){//新城开发公司合同台账wb = importExcellModel(baseExcelModelUrl+excelModelName3);}else if("gczjzxwttz".equals(modelName)){//工程造价咨询委托台账wb = importExcellModel(baseExcelModelUrl+excelModelName4);}else if("flgwgztz".equals(modelName)){//法律顾问工作台账wb = importExcellModel(baseExcelModelUrl+excelModelName5);}else if("jhhybhtgztz".equals(modelName)){//计划合约部合同工作台帐wb = importExcellModel(baseExcelModelUrl+excelModelName6);}else if("jhhybzbcgtz_xe".equals(modelName)){//计划合约部招标采购台账-限额wb = importExcellModel(baseExcelModelUrl+excelModelName7);}else if("jhhyb_gc".equals(modelName)){// 工程  fsxc_jhhyb_gc_modelwb = importExcellModel(baseExcelModelUrl+excelModelName8);}else{return null;}sheet = wb.getSheetAt(0);
//设置建表时间数据Calendar c = Calendar.getInstance();int year = c.get(Calendar.YEAR);int mouth = c.get(Calendar.MONTH) + 1;int day = c.get(Calendar.DAY_OF_MONTH);Map<String, Object> replaceDataMap = new HashMap<String, Object>();replaceDataMap.put("year", String.valueOf(year));replaceDataMap.put("mouth", String.valueOf(mouth));replaceDataMap.put("day",String.valueOf(day));replaceCellValue(replaceDataMap, sheet);//导入数据int rowNum = 3;sheet.shiftRows(rowNum+1, sheet.getPhysicalNumberOfRows(), dataArray.size());HSSFCellStyle cellStyle = wb.createCellStyle();cellStyle.setWrapText(true);cellStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中cellStyle.setBorderBottom((short) 1);cellStyle.setBorderLeft((short) 1);cellStyle.setBorderRight((short) 1);cellStyle.setBorderTop((short) 1);int colNum = -1;for (int i = 0; i < dataArray.size(); i++) {//数据Map<String, Object> dataMap = dataArray.get(i);//创建行HSSFRow row = sheet.createRow(++rowNum);//序号列cell = row.createCell(++colNum);cell.setCellValue(i + 1);cell.setCellStyle(cellStyle);//数据列for(int j=0;j<fieldName.length;j++){cell = row.createCell(++colNum);cell.setCellValue(dataMap.get(fieldName[j].toLowerCase()).toString());cell.setCellStyle(cellStyle);}colNum = -1;}return wb;}public static float getExcelCellAutoHeight(String str, float fontCountInline) {float defaultRowHeight = 12.00f;// 每一行的高度指定float defaultCount = 0.00f;for (int i = 0; i < str.length(); i++) {float ff = getregex(str.substring(i, i + 1));defaultCount = defaultCount + ff;}return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;// 计算}
public static float getregex(String charStr) {if (charStr == " ") {return 0.5f;}// 判断是否为字母或字符if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) {return 0.5f;}// 判断是否为全角
if (Pattern.compile("[u4e00-u9fa5]+$").matcher(charStr).matches()) {return 1.00f;}// 全角符号 及中文if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {return 1.00f;}return 0.5f;}/** * 用HSSFWorkbook生成excel文件在服务器 *  * @param excelName * @param wb * @throws FileNotFoundException * @throws IOException */public static boolean generateExcel(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException {try {// 输出文件String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls";File fileOut = new File(writeExcelUrl);FileOutputStream os = new FileOutputStream(fileOut);wb.write(os);close(os);} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();return false;}return true;}/** * 用HSSFWorkbook生成excel文件在服务器 *  * @param excelName * @param wb * @throws FileNotFoundException * @throws IOException */public static String generateExcel2(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException {String dz = "";try {// 输出文件String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls";File fileOut = new File(writeExcelUrl);FileOutputStream os = new FileOutputStream(fileOut);wb.write(os);close(os);dz = fileName+".xls";} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();return "";}return dz;}
/** * 用HSSFWorkbook生成excel文件给用户下载 *  * @param excelName * @param wb * @throws IOException  * @throws FileNotFoundException * @throws IOException */public static boolean generateExcel(HttpServletResponse response,String fileName, HSSFWorkbook wb){try {setResponseHeader(response, fileName);OutputStream os = response.getOutputStream();wb.write(os);close(os);} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();return false;}return true;}/**     * 关闭输出流     * @param os     */    private static void close(OutputStream os) {        if (os != null) {            try {            os.flush();                os.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }/** * 发送响应流方法 * @param response * @param fileName */    public static void setResponseHeader(HttpServletResponse response, String fileName) {        try {            try {                fileName = new String((fileName+".xls").getBytes("UTF-8"),"ISO8859-1");                //fileName = new String(fileName.getBytes(),"ISO8859-1");            } catch (UnsupportedEncodingException e) {                e.printStackTrace();            }            response.reset();            response.setContentType("application/msexcel");            //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");        } catch (Exception ex) {            ex.printStackTrace();        }    }/** * xls打包成zip进行下载 */public String downloads(String[] filepath, HttpServletResponse response,String name) throws IOException, ServletException {Date day = new Date();SimpleDateFormat df = new SimpleDateFormat("HHmmss");// 要生成的压缩文件地址和文件名称String fileName = name + df.format(day) + ".zip";String path = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName;File zipFile = new File(path);ZipOutputStream zipStream = null;FileInputStream zipSource = null;BufferedInputStream bufferStream = null;try {// 构造最终压缩包的输出流zipStream = new ZipOutputStream(new FileOutputStream(zipFile));for (int i = 0; i < filepath.length; i++) {File file = new File(System.getProperty("catalina.home")+ "/webapps/webdav/" + filepath[i]);// 将需要压缩的文件格式化为输入流zipSource = new FileInputStream(file);// 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样ZipEntry zipEntry = new ZipEntry(file.getName());// 定位该压缩条目位置,开始写入文件到压缩包中zipStream.putNextEntry(zipEntry);// 输入缓冲流bufferStream = new BufferedInputStream(zipSource, 1024 * 10);int read = 0;// 创建读写缓冲区byte[] buf = new byte[1024 * 10];while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) {zipStream.write(buf, 0, read);}}} catch (Exception e) {e.printStackTrace();} finally {// 关闭流try {if (null != bufferStream)bufferStream.close();if (null != zipStream)zipStream.close();if (null != zipSource)zipSource.close();} catch (IOException e) {e.printStackTrace();}}
return fileName;/* * //2.获取要下载的文件名 String fileName = * path.substring(path.lastIndexOf("\")+1); * //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 File fi=new File(path); * response.setHeader("Content-Disposition", * "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")); * response.addHeader("Content-Length", "" + fi.length()); * response.setContentType("application/octet-stream"); //4.获取要下载的文件输入流 * InputStream in = new FileInputStream(fi); int len = 0; //5.创建数据缓冲区 * byte[] buffer = new byte[1024]; //6.通过response对象获取OutputStream流 * OutputStream out = response.getOutputStream(); * //7.将FileInputStream流写入到buffer缓冲区 while ((len = in.read(buffer)) > 0) * { //8.使用OutputStream将缓冲区的数据输出到客户端浏览器 out.write(buffer,0,len); } * in.close(); */}
public static void main(String[] args) {/* 模板名 * bmlxhqdjb //部门立项会签登记表 * jhhybzbcgtz //计划合约部招标采购台账 * xckfgshttz //新城开发公司合同台账 * gczjzxwttz //工程造价咨询委托台账 * flgwgztz //法律顾问工作台账 * jhhybhtgztz //计划合约部合同工作台帐 * jhhybzbcgtz_xe //计划合约部招标采购台账-限额 *  * 数据 * 需要导出的数据 *  * 导出时列的属性名顺序 * 注意与数据的字段要对应 *///HSSFWorkbook wb = createHSSFSheet(模板名,数据,导出时列的属性名顺序);/*try{ *if(generateExcel(response对象,导出文件的名字,wb)){ *//导出成功 *} *}catch (Exception e) { *//导出失败 *} */}}
原文地址:https://www.cnblogs.com/mysterious-killer/p/10905873.html