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. 洛谷 P1862 输油管道问题

    题意 题目链接:P1862 输油管道问题 不难看出每个油井的 \(x\) 坐标是没用的,所以问题转化为如下. 代数意义:给出 \(n\) 个数 \(y_1,y_2,\ldots,y_n\),找一个数 ...

  2. 透过 Chrome 深入理解浏览器导航过程

    网络的导航,是从输入 url 到最终获取到文件的过程.其中牵扯到浏览器架构.操作系统.网络等一系列知识.本文将从各个角度详细论述这一过程,涉及广度与深度.如果您是已经有一定基础的同学,那么本文可以快速 ...

  3. 飞猪基于 Serverless 的云+端实践与思考

    作者 | 王恒飞(承荫) 本文整理自飞猪旅行前端技术专家--王恒飞(承荫)在[阿里云 Serverless Developer Meetup 上海站]上的分享.点击查看直播回放:https://dev ...

  4. 浅析InnoDB引擎的索引和索引原理

    浅析InnoDB引擎的索引和索引原理 什么是InnoDB的索引 InnoDB的索引就是一颗B+树.页是InnoDB引擎在内存和磁盘之间交换数据的基本单位,页的大小一般是16KB,页的大小可以在启动My ...

  5. 枚举类型(enum)

    关于枚举 枚举类型是Java 5中新增特性的一部分,它是一种特殊的数据类型,之所以特殊是因为它既是一种类(class)类型却又比类类型多了些特殊的约束,但是这些约束的存在也造就了枚举类型的简洁性.安全 ...

  6. Scrum Meeting 0427

    零.说明 日期:2021-4-27 任务:简要汇报两日内已完成任务,计划后两日完成任务 一.进度情况 组员 负责 两日内已完成的任务 后两日计划完成的任务 qsy PM&前端 完成部分登录,注 ...

  7. Spring Cloud Gateway 网关限流

    Spring Cloud Gateway 限流 一.背景 二.实现功能 三.网关层限流 1.使用默认的redis来限流 1.引入jar包 2.编写配置文件 3.网关正常响应 4.网关限流响应 2.自定 ...

  8. Prometheus监控Canal

    Prometheus监控Canal 一.背景 二.实现步骤 1.修改prometheus.yml配置文件 2.启动prometheus 3.查看prometheus是否成功接入canal 4.cana ...

  9. Docker制作能够ssh连接的镜像

    本类文章只作为记录使用 命令操作: #拉取Centos 7 docker pull centos:7 #运行一个镜像 docker run -tdi --privileged centos:7 ini ...

  10. Noip模拟63 2021.9.27(考场惊现无限之环)

    T1 电压机制 把题目转化为找那些边只被奇数环包含. 这样的话直接$dfs$生成一棵树,给每个点附上一个深度,根据其他的非树边都是返祖边 可以算出环内边的数量$dep[x]-dep[y]+1$,然后判 ...