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) { *//导出失败 *} */}}

Excel - java的更多相关文章

  1. 导出excel java实现

    1.前台页面代码: <tr> <td><input dataId="excel" type="button" value=&quo ...

  2. HSSFWorkbook 导出excel java

    public String exportExcelList(){ //创建webbook,对应一个excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //在we ...

  3. poi 导出Excel java代码

    js: function initBatchExport(url,sub_key,current_sub_num){ var btn_id="#btn_char"+current_ ...

  4. JXL 读取 Excel java中jxl导出数据到excel的例子 上传文件

    2010-10-14 19:17:06 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info 信息: Entferne Dat ...

  5. java的poi技术写Excel的Sheet

    在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...

  6. JAVA 操作Excel工具类

    Bean转Excel对象 /* * 文件名:BeanToExcel.java */ import java.util.ArrayList; import java.util.List; import ...

  7. Java将数据写进excel

    Java将数据写进excel Java将数据写进excel class User { private String name ; private String password; public Use ...

  8. 通过java反射实现的excel数据导出

    Excel.java @SuppressWarnings("deprecation") public static <T> void ExportExcel(Strin ...

  9. Java添加、读取Excel公式

    操作excel表格用公式来处理数据时,可通过创建公式来运算数据,或通过读取公式来获取数据信息来源.本文以通过Java代码来演示在Excel中创建及读取公式的方法.这里使用了Excel Java类库(F ...

随机推荐

  1. 实现线程按顺序输出ABC

    线程按顺序输出ABC 实现描述:建立三个线程A.B.C,分别按照顺序输出十次ABC 首先建立一个方法,按照条件进行输出 class PrintABC{ private int index=0; pub ...

  2. NOIP 模拟 六十九

    0+30+40+90, 菜..... T1 取石子 考试扔了将近两个小时,最后也没有回忆起博弈论的相关内容.. 现在只会50pts.正解待补. #include<bits/stdc++.h> ...

  3. MySQL8.0.20安装教程,MySQL8.0.20安装详细图文教程

    1.下载链接如下: MySQL8.0.20版本 https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-20.html 其他版本:MySQL8 ...

  4. mysql从零开始之MySQL UPDATE 更新

    MySQL UPDATE 更新 如果我们需要修改或更新 MySQL 中的数据,我们可以使用 SQL UPDATE 命令来操作. 语法 以下是 UPDATE 命令修改 MySQL 数据表数据的通用 SQ ...

  5. UE4技术总结——委托

    UE4技术总结--委托 目录 UE4技术总结--委托 一.定义 二.用法 2.1 声明与调用委托 2.1.1 单播委托 2.1.1.a 声明 2.1.1.b 绑定 2.1.1.c 执行委托 2.1.1 ...

  6. CTF入门记录(1

    (https://ctf-wiki.org) 00 基础了解 CTF简介 (wolai.com) 00-1 CTF题目类型 Web 大部分情况下和网.Web.HTTP等相关技能有关. Web攻防的一些 ...

  7. MyBatis概念和”安装“

    MyBatis概念 MyBatis的前身就是iBatis,本是apache的一个开源项目,2010年这个项目由apahce sofeware foundation 迁移到了google code,并且 ...

  8. HttpServletRequest 入门

    1. request对象和response对象的原理 request和response对象是由服务器创建的.我们来使用它们 request对象是来获取请求消息,response对象是来设置响应消息 2 ...

  9. SoapUI入门实例

    一.Soapui介绍 WSDL(Web Services Description Language)就是这样一个基于XML的语言,用于描述Web Service及其函数.参数和返回值.它是WebSer ...

  10. 提升使用Linux效率的小操作

    提升使用Linux效率的小操作 保存更新? 本文记录了个人在使用Linux时觉得好用的一些快捷方式/功能: 为那种知道了能提高效率,但是的不知道也并没有影响的操作. 历史命令 该操作用于快速查看已使用 ...