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. Winform 控件命名规范

    前言 最近 Winform 项目做得比较多,控件命名规范上常用的能记住,但是有些总要查,写个记录吧.方便以后自己用,大家也可以参考. 标准控件 序号 控件类型简写 控件类型 1 btn Button ...

  2. 分布式、微服务必须配个日志管理系统才优秀,Exceptionless走起~~~

    前言 在真实的项目中,不管是功能日志.错误日志还是异常日志,已经是项目的重要组成部分.在原始的单体架构,通常看日志的方式简单粗暴,直接登录到服务器,把日志文件拷贝下来进行分析:而如今分布式.微服务架构 ...

  3. Go语言之数组与切片基础

    一.数组 数组是同一类型元素的集合,可以放多个值,但是类型一致,内存中连续存储 Go 语言中不允许混合不同类型的元素,而且数组的大小,在定义阶段就确定了,不能更改 1.数组的定义 // 定义一个大小为 ...

  4. 沈抚示范区·“华为云杯”2021全国AI大赛圆满落

    摘要:以赛促学,赛教结合!驱动AI产业繁荣发展 本文分享自华为云社区<云聚沈抚 · 智赢未来!沈抚示范区·"华为云杯"2021全国AI大赛圆满落幕>,作者:灰灰哒. 近 ...

  5. 10.13 Nginx 负载均衡

    七层负载均衡server { listen 80; server_name localhost; location / { proxy_pass http://name; //调用集群 } } ups ...

  6. Java编译运行环境讨论(复古但能加深对Java项目的理解)

    Java编译运行环境讨论(复古但能加深对Java项目的理解) 如今我们大多数情况都会使用IDE来进行Java项目的开发,而一个如今众多优秀的IDE已经能够帮助我们自动的部署并调试运行我们的Java程序 ...

  7. NOIP2012提高组初赛NB题

    本题中,我们约定布尔表达式只能包含 p, q, r 三个布尔变量,以及"与"(∧)."或"(∨)."非"(¬)三种布尔运算.如果无论 p, ...

  8. 题解 [HNOI2016]大数

    题目传送门 题目大意 给出一个\(n\)个数的字符串,有\(m\)次查询,对于该串的子串\([l,r]\)有多少个子串满足是固定素数\(p\)的倍数. 思路 其实很简单,但是一开始想偏了...果然还是 ...

  9. OutOfMemoryException异常解析

    一.概述 在国庆休假快结束的最后一天晚上接到了部门老大的电话,某省的服务会出现崩溃问题.需要赶紧修复,没错这次的主角依旧是上次的"远古项目"没有办法同事都在休假没有人能帮忙开电脑远 ...

  10. 【Java虚拟机9】类加载器之命名空间详解

    前言 前面介绍类加载器的时候,介绍了一下命名空间这个概念.今天就通过一个例子,来详细了解一下[类加载器的命名空间].然后通过这个例子,我们可以总结一下双亲委托模型的好处与优点. 例1(不删除class ...