Excel - java
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的更多相关文章
- 导出excel java实现
1.前台页面代码: <tr> <td><input dataId="excel" type="button" value=&quo ...
- HSSFWorkbook 导出excel java
public String exportExcelList(){ //创建webbook,对应一个excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //在we ...
- poi 导出Excel java代码
js: function initBatchExport(url,sub_key,current_sub_num){ var btn_id="#btn_char"+current_ ...
- JXL 读取 Excel java中jxl导出数据到excel的例子 上传文件
2010-10-14 19:17:06 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info 信息: Entferne Dat ...
- java的poi技术写Excel的Sheet
在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...
- JAVA 操作Excel工具类
Bean转Excel对象 /* * 文件名:BeanToExcel.java */ import java.util.ArrayList; import java.util.List; import ...
- Java将数据写进excel
Java将数据写进excel Java将数据写进excel class User { private String name ; private String password; public Use ...
- 通过java反射实现的excel数据导出
Excel.java @SuppressWarnings("deprecation") public static <T> void ExportExcel(Strin ...
- Java添加、读取Excel公式
操作excel表格用公式来处理数据时,可通过创建公式来运算数据,或通过读取公式来获取数据信息来源.本文以通过Java代码来演示在Excel中创建及读取公式的方法.这里使用了Excel Java类库(F ...
随机推荐
- Mybatis里@InsertProvider、@UpdateProvider方法里使用if test标签
例如: ··· insert into TEST1(<if test="base_id!=null and base_id!=''">base_id,</if&g ...
- Win32窗口框架
Win32窗口框架 WindowClass 单例,负责窗口初始化注册和取消注册: 负责提供静态方法: 放在Window类内部,方便初始化时,wndProc(HandleMsgSetup)的赋值: cl ...
- 1-基本建表sql语句
基本的建表语句的总结 --建表语法 CREATE TABLE 表名( --约束可以没有 列名1 数据类型 [约束], 列名2 数据类型 [约束], ......, [约束], ..... ); --该 ...
- Intellij IDEA使用姿势
Intellij IDEA 智能补全的 10 个姿势,太牛逼了.. Intellij Idea非常6的10个姿势
- 微信小程序中路由跳转
一.是什么 微信小程序拥有web网页和Application共同的特征,我们的页面都不是孤立存在的,而是通过和其他页面进行交互,来共同完成系统的功能 在微信小程序中,每个页面可以看成是一个pageMo ...
- vue3.x自定义组件双向数据绑定v-model
vue2.x 语法 在 2.x 中,在组件上使用 v-model 相当于绑定 value prop 并触发 input 事件: <ChildComponent v-model="pag ...
- 【二食堂】Beta - Scrum Meeting 10
Scrum Meeting 10 例会时间:5.25 18:30~18:50 进度情况 组员 当前进度 今日任务 李健 1. 继续文本导入.保存部分的工作issue 2. 完成了技术博客 1. 继续文 ...
- BUAA软件工程个人项目作业
BUAA软件工程个人项目作业 项目 内容 这个作业属于哪个课程 2020春季计算机学院软件工程(罗杰 任健) 这个作业的要求在哪里 个人项目作业 我在这个课程的目标是 学习软件开发的流程 这个作业在哪 ...
- 微服务(三) Eureka注册中心和Ribbon负载均衡
1. Eureka注册中心 1.1 Eureka的结构和作用 在上一篇文章中 微服务(二)服务拆分及远程调用 order-service在发起远程调用的时候,该如何得知user-service实例的i ...
- Spring Cloud Gateway 网关限流
Spring Cloud Gateway 限流 一.背景 二.实现功能 三.网关层限流 1.使用默认的redis来限流 1.引入jar包 2.编写配置文件 3.网关正常响应 4.网关限流响应 2.自定 ...