您的位置:首页 > 编程语言 > Java开发

java 导出数据到指定的excel模板中。

2013-12-16 17:41 525 查看



为什么这样写呢,因为这样写方便修改,不会出太多的乱子!直奔主题:

使用的JXL包

结果:



EXCEL样式:



页面样式:



网页页面链接:

location.href = "physical.do?method=InitDownLoad&downLoadPath="+ encodeURIComponent(encodeURIComponent(downLoadPath));

location.href是打开窗口并自动下载,这个很重要

下面是后台代码:

后台代码分了七个类,有6是公共方法为一个类服务,我贴顺序是主要,次要。。。。。

ExcelTool.java



package com.hna.aircrewhealth.excel.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.hna.aircrewhealth.po.AviatorHealthCheck;
import com.hna.aircrewhealth.security.po.Staff;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;

import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExcelTool {

private static String path = "F:\\luokq\\aircrewhealth\\template\\重大疾病报告单.xls";
private final static String defaultName = "航医跟班检查记录单.xls";

public static String getPath() {
return path;
}

public static void setPath(String p) {
path = p;
}
  //这个MAIN方法是个DEMO 可以参照这个写法
public static void main(String[] arg) {
AviatorHealthCheck bean = new AviatorHealthCheck();

bean.setId("3FCB19B440E74DF1BD50CD123A3C087C");
bean.setHealthCheckFlightNum("NB-38-54321");

Staff s = new Staff(); //声明一个实体类
s.setName("王八");
bean.setFollowDoctor(s);

bean.setNoddeid("878787");
bean.setStartTime("1987-02-25");
bean.setEndTime("1987-02-25");
bean.setFollowContext("脸可大饿,打瞌睡,而开发,奥东科咳咳咳什么刺激附近的库斯科到看风景的库斯科,道可服务端");

Map<String, Object> map = new HashMap<String, Object>();   //声明一个map
map.put("AviatorHealthCheck", bean);  //将实体放入Map,因为是按Map输出的
/**
*下面这个是循环用的
*/
List<Object> list = new ArrayList<Object>();

for (int i = 0; i < 6; i++) {
bean = new AviatorHealthCheck();

bean.setId("3FCB19B440E74DF1BD50CD123A3C087C"+"----"+i);
bean.setHealthCheckFlightNum("NB-38-54321"+"----"+i);

s = new Staff();
s.setName("王八"+"----"+i);
bean.setFollowDoctor(s);

bean.setNoddeid("878787"+"----"+i);
bean.setStartTime("1987-02-25"+"----"+i);
bean.setEndTime("1987-02-25"+"----"+i);
bean.setFollowContext("脸可大饿,打瞌睡,而开发,奥东科咳咳咳什么刺激附近的库斯科到看风景的库斯科,道可服务端"+"----"+i);
list.add(bean);
}
map.put("listname", list);
map.put("listname2", list);
/**这是循环结束了*/
exportExcel(path, map);   //这个最主要,是导出Excel的方法
}

/**
* 导出 Excel
*
* @param template
*            Excel模板
* @param datas
*            数据
* @return
*/
public static FileInputStream exportExcel(String template, Map<String, Object> datas) {
FileInputStream fis = null;
InputStream is = FileTool.getFileInputStream(template);

try {
if (is != null) {
Workbook book = Workbook.getWorkbook(is);
File tempFile = File.createTempFile("temp", ".xls");

WritableWorkbook wWorkbook = Workbook.createWorkbook(tempFile, book);

/** 处理【表达式】类型的数据。 **/
generateExpData(book, wWorkbook, datas);
/** 处理【循环结果集】类型的数据。 **/
generateEachData(book, wWorkbook, datas);

wWorkbook.write();
wWorkbook.close();

fis = new FileInputStream(tempFile);
}
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return fis;
}

public static FileInputStream exportExcel1(String template, Map<String, Object> datas) {
FileInputStream fis = null;
InputStream is = FileTool.getFileInputStream(template);

try {
if (is != null) {
Workbook book = Workbook.getWorkbook(is);
File tempFile = File.createTempFile("temp", ".xls");
WritableWorkbook wWorkbook = Workbook.createWorkbook(tempFile, book);

/** 处理【表达式】类型的数据。 **/
generateExpData1(book, wWorkbook, datas);
/** 处理【循环结果集】类型的数据。 **/
generateEachData(book, wWorkbook, datas);

wWorkbook.write();
wWorkbook.close();

fis = new FileInputStream(tempFile);
}
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return fis;
}
/**
* 处理【表达式】类型的数据。
*
* @param book
*            【模板】对象
* @param wWorkbook
*            根据模板创建的【新数据文件】对象
*/
private static void generateExpData(Workbook book, WritableWorkbook wWorkbook, Map<String, Object> datas) throws Exception {
List<ExcelCells> expcells = search("${", book);
for (ExcelCells cell : expcells) {
wWorkbook.getSheet(cell.getSheetIndex()).addCell(getValueByExp(cell, datas));
}
}

private static void generateExpData1(Workbook book, WritableWorkbook wWorkbook, Map<String, Object> datas) throws Exception {
List<ExcelCells> expcells = search("${", book);
for (ExcelCells cell : expcells) {
wWorkbook.getSheet(cell.getSheetIndex()).addCell(getValueByExp1(cell, datas));
}
}

/**
* 处理【循环结果集】类型的数据
*
* @param book
*            【模板】对象
* @param wWorkbook
*            根据模板创建的【新数据文件】对象
*/
private static void generateEachData(Workbook book, WritableWorkbook wWorkbook, Map<String, Object> datas) throws Exception {
List<ExcelCells> each = search("each.", book);
/* 先对模板列对象,进行分组。 */
Map<String, List<ExcelCells>> map = new LinkedHashMap<String, List<ExcelCells>>();//
for (ExcelCells cell : each) {
String[] array = cell.getCell().getContents().trim().split("\\.");
if (array.length >= 3) {
List<ExcelCells> list = map.get(array[0] + "." + array[1]);
if (list == null) {
list = new ArrayList<ExcelCells>();
map.put(array[0] + "." + array[1], list);
}
list.add(cell);
}
}

Iterator<String> iterator = map.keySet().iterator();

int insertrow = 0;//标识当前工作表新增了多少条数据。
int lastSheetIndex = -1;//标识上一次工作表的下标。

while (iterator.hasNext()) {
List<ExcelCells> list = map.get(iterator.next());
int sheetIndex = list.get(0).getSheetIndex();// 获取面板下标。
//当切换工作表事  insertrow 清 0
if(lastSheetIndex != -1 && lastSheetIndex != sheetIndex) insertrow = 0;
lastSheetIndex = sheetIndex;

int startRow = list.get(0).getCell().getRow() + insertrow;// 获取开始行下标。

String[] array = list.get(0).getCell().getContents().trim().split("\\.");
if (array.length > 0) {
Object data = datas.get(array[1]);
if (data != null && !data.getClass().getName().equals(List.class.getName()) && !data.getClass().getName().equals(ArrayList.class.getName())) {
throw new Exception("数据:" + array[1] + "不是一个集合类!");
}
List<Object> rowsData = (List<Object>) data;
// 有数据时。
if (rowsData != null && rowsData.size() > 0) {
for (int i = 0; i < rowsData.size(); i++) {
/* 第一行数据,覆盖模板位置,所以不需要创建新行 */
if (i == 0) {
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, rowsData.get(i), startRow, cell.getCell().getColumn()));
}
continue;
}
/* 创建新行 */
wWorkbook.getSheet(sheetIndex).insertRow(startRow + i);
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, rowsData.get(i), startRow + i, cell.getCell().getColumn()));
}
insertrow++;
}

}
// 无数据时。
else {
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, null, startRow, cell.getCell().getColumn()));
}
}
}
}

}

/**
* 根据【表达式】从数据集中获取相应数据。
*
* @param exp
*            表达式
* @param datas
*            数据集
* @return
*/
public static WritableCell getValueByExp(ExcelCells cells, Map<String, Object> datas) {
WritableCell writableCell = null;

List<Object> values = new ArrayList<Object>();
List<String> exps = cells.getExps();// 获取表达式集合。

String old_c = cells.getCell().getContents();// 模板原内容。

for (String exp : exps) {

String[] names = exp.replace("${", "").replace("}", "").split("\\.");

Object object = null;
for (String name : names) {
if (object == null)
object = ObjectCustomUtil.getValueByFieldName(name, datas);
else
object = ObjectCustomUtil.getValueByFieldName(name, object);
}
// ${asd.sdfa}
if (!old_c.isEmpty()) {
while (old_c.indexOf(exp) != -1)
old_c = old_c.replace(exp, object.toString());
}
}

writableCell = getWritableCellByObject(cells.getCell().getRow(), cells.getCell().getColumn(), old_c);
writableCell.setCellFormat(cells.getCell().getCellFormat());

return writableCell;
}

/*
* 这个方法是专门用于驻外机组环境卫生检查
*/
public static WritableCell getValueByExp1(ExcelCells cells, Map<String, Object> datas) {
WritableCell writableCell = null;

List<Object> values = new ArrayList<Object>();
List<String> exps = cells.getExps();// 获取表达式集合。

String old_c = cells.getCell().getContents();// 模板原内容。

for (String exp : exps) {

String[] names = exp.replace("${", "").replace("}", "").split("\\.");

Object object = null;
String checkContentValue = "";
for (String name : names) {
if (object == null){
object = ObjectCustomUtil.getValueByFieldName(name, datas);
}else{
object = ObjectCustomUtil.getValueByFieldName(name, object);
}
if(name.indexOf("checkContent")!=-1){
if("0".equals(object.toString())){
checkContentValue = "符合";
}else if("1".equals(object.toString())){
checkContentValue = "不符合";
}else{
checkContentValue = "未检查";
}
}else if(name.indexOf("checkTime")!=-1){
Date date = (Date)object;
checkContentValue = date.getYear()+"年"+ (date.getMonth()+1) +"月" +date.getDate();
}
}

if (!old_c.isEmpty()) {
while (old_c.indexOf(exp) != -1){
if("".equals(checkContentValue)){
old_c = old_c.replace(exp, object.toString());
}else{
old_c = old_c.replace(exp, checkContentValue);
}
}
}
}

writableCell = getWritableCellByObject(cells.getCell().getRow(), cells.getCell().getColumn(), old_c);
writableCell.setCellFormat(cells.getCell().getCellFormat());

return writableCell;
}

/**
* 根据【Each表达式】从数据集中获取相应数据。
*
* @param exp
*            表达式
* @param datas
*            数据集
* @return
*/
public static WritableCell getValueByEach(ExcelCells cells, Object datas, int rows, int column) {
WritableCell writableCell = null;

if (datas != null) {
List<Object> values = new ArrayList<Object>();
String[] exps = cells.getCell().getContents().trim().split("\\.");// 获取表达式集合。

Object object = null;
for (int i = 2; i < exps.length; i++) {
if (object == null)
object = ObjectCustomUtil.getValueByFieldName(exps[i], datas);
else
object = ObjectCustomUtil.getValueByFieldName(exps[i], object);
}
writableCell = getWritableCellByObject(rows, column, object);
} else {
writableCell = getWritableCellByObject(rows, column, null);
}
writableCell.setCellFormat(cells.getCell().getCellFormat());

return writableCell;
}

/**
* 【未实现】
*
* @param beginRow
* @param beginColumn
* @param heads
* @param result
* @return
*/
public static synchronized String customExportExcel(int beginRow, int beginColumn, Map heads, List result) {
return null;
}

/**
* 根据提供的【列标】、【行标】、【对象值】构建一个Excel列对象。
*
* @param beginRow
*            【行标】
* @param beginColumn
*            【列标】
* @param obj
*            【对象值】
* @return
*/
public static WritableCell getWritableCellByObject(int beginRow, int beginColumn, Object obj) {
WritableCell cell = null;

if (obj == null)
return new Label(beginColumn, beginRow, "");
if (obj.getClass().getName().equals(String.class.getName())) {
cell = new Label(beginColumn, beginRow, obj.toString());
} else if (obj.getClass().getName().equals(int.class.getName()) || obj.getClass().getName().equals(Integer.class.getName())) {
// jxl.write.Number
cell = new Number(beginColumn, beginRow, Integer.parseInt(obj.toString()));
} else if (obj.getClass().getName().equals(float.class.getName()) || obj.getClass().getName().equals(Float.class.getName())) {
cell = new Number(beginColumn, beginRow, Float.parseFloat(obj.toString()));
} else if (obj.getClass().getName().equals(double.class.getName()) || obj.getClass().getName().equals(Double.class.getName())) {
cell = new Number(beginColumn, beginRow, Double.parseDouble(obj.toString()));
} else if (obj.getClass().getName().equals(long.class.getName()) || obj.getClass().getName().equals(Long.class.getName())) {
cell = new Number(beginColumn, beginRow, Long.parseLong(obj.toString()));
} else if (obj.getClass().getName().equals(Date.class.getName())) {
cell = new DateTime(beginColumn, beginRow, (Date)obj);
} else {
cell = new Label(beginColumn, beginRow, obj.toString());
}
return cell;
}

/**
* 查找某字符第一次出现的位置。
*
* @param text
*            【文本】
* @param book
*            【Excel对象】
* @return
*/
public static ExcelCells searchFirstText(String text, Workbook book) {
ExcelCells Rcell = null;
Sheet[] sheets = book.getSheets();
if (sheets != null) {
int sheetIndex = 0;
for (Sheet sheet : sheets) {
if (sheet != null) {
int rows = sheet.getRows();
if (rows > 0) {
for (int i = 0; i < rows; i++) {
Cell[] cells = sheet.getRow(i);
if (cells != null) {
for (Cell cell : cells) {
if (cell != null && !StringUtils.isNull(cell.getContents())) {
String contents = cell.getContents();
if (contents.equals(text))
return new ExcelCells(sheet, cell, sheetIndex);
}
}
}
}
}
}
sheetIndex++;
}
}
return Rcell;
}

/**
* 查找包含某字符所有的列对象。
*
* @param text
*            【文本】
* @param book
*            【Excel对象】
* @return
*/
public static List<ExcelCells> search(String text, Workbook book) {
List<ExcelCells> rcells = new ArrayList<ExcelCells>();

Sheet[] sheets = book.getSheets();
if (sheets != null)
for (Sheet sheet : sheets) {
if (sheet != null) {
int rows = sheet.getRows();
if (rows > 0) {
for (int i = 0; i < rows; i++) {
Cell[] cells = sheet.getRow(i);
if (cells != null) {
for (Cell cell : cells) {
if (cell != null && !StringUtils.isNull(cell.getContents())) {
String contents = cell.getContents();
if (contents.indexOf(text) != -1)
rcells.add(new ExcelCells(sheet, cell));
}
}
}
}
}
}
}
return rcells;
}

}




DateTool.java



package com.hna.aircrewhealth.excel.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTool {
public static Date parse(String string) {
try {
DateFormat format = DateFormat.getDateInstance();
return format.parse(string);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 获取当前日期时间
*
* @return
*/
public static String getTodayTime() {
Date sellTime = new Date();

Calendar cal = Calendar.getInstance();
cal.setTime(sellTime);
System.out.println(cal.toString());
DateFormat format = DateFormat.getDateInstance();

System.out.println(format.format(sellTime));
return null;
}

/**
* 获取当天日期(短日期)
*
* @return
*/
public static String getTodayDate() {
Date sellTime = new Date();
SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd");
return dateformat1.format(sellTime);
}

public static String getMonth_day(Date date, String str) {
if (str == null)
str = "/";
Calendar cal = Calendar.getInstance();
cal.setTime(date);

return (cal.get(Calendar.MONTH) + 1) + str + cal.get(Calendar.DAY_OF_MONTH);
}

/**
* 获取当天日期(长日期)
*
* @return
*/
public static String getTodayDateLong() {
Date sellTime = new Date();
SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateformat1.format(sellTime);
}

/**
* 获取当前年份
*
* @author zl 2011-10-24
* @return
*/
public static int currentYear() {

Calendar cal = Calendar.getInstance();

int year = cal.get(Calendar.YEAR);
// int month = cal.get(Calendar.MONTH )+1;

// System.out.println(year + " 年 " + month + " 月");

return year;
}

/**
* 将日期格式化
*
* @param date
* @param arg
* @return
*/
public static String format(Date date, String arg) {
if (date == null)
return null;
if (arg == null)
arg = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(arg);
return sdf.format(date);
}

public static Date stringToDate(String str) throws ParseException {
if (str.split("-").length == 2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
return sdf.parse(str);
} else if(str.split("-").length == 1){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
return sdf.parse(str);
} else{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(str);
}

}

//计算俩个日期之间有多少天
public static int countDays(String begin,String end){
int days = 0;

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar c_b = Calendar.getInstance();
Calendar c_e = Calendar.getInstance();

try{
c_b.setTime(df.parse(begin));
c_e.setTime(df.parse(end));

while(c_b.before(c_e)){
days++;
c_b.add(Calendar.DAY_OF_YEAR, 1);
}

}catch(ParseException pe){
System.out.println("日期格式必须为:yyyy-MM-dd;如:2010-4-4.");
}

return days;
}

//计算当前距离当前日期之后的某个日期
public static String addCalendarDay(Date calDate, long addDate) {
long time = calDate.getTime();
addDate = addDate * 24 * 60 * 60 * 1000;
time += addDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(new Date(time));
}

public static Date addDay(Date calDate, long addDate) {
long time = calDate.getTime();
addDate = addDate * 24 * 60 * 60 * 1000;
time += addDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return new Date(time);
}

//计算距离执行日期提前多少天的日期
public static Date reduceDay(Date calDate, long addDate) {
long time = calDate.getTime();
addDate = addDate * 24 * 60 * 60 * 1000;
time -= addDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return new Date(time);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// DateTool.getTodayTime();
// DateTool.currentYear();

try {
//System.out.println(DateTool.stringToDate("2001-10-10"));
Date date=new Date();
System.out.println(DateTool.addCalendarDay(date,1));
//System.out.println(DateTool.countDays("2012-4-10","2012-4-24"));

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}




日期类型的转换哈

ExcelCells.java



package com.hna.aircrewhealth.excel.utils;

import java.util.ArrayList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;

public class ExcelCells {
public final static String regex = "\\$\\{[^\\}]+\\}";
private Sheet sheet ;
private Cell cell ;
private int sheetIndex;

public ExcelCells(){}

public ExcelCells(Sheet sheet,Cell cell){
this.sheet = sheet;
this.cell = cell;
}
public ExcelCells(Sheet sheet,Cell cell,int sheetIndex){
this.sheet = sheet;
this.cell = cell;
this.sheetIndex = sheetIndex;
}

public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public Cell getCell() {
return cell;
}
public void setCell(Cell cell) {
this.cell = cell;
}
public int getSheetIndex() {
return sheetIndex;
}
public void setSheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
}

/**
* 获取当前列当中【表达式】集合
* @return
*/
public List<String> getExps(){
List<String> list = new ArrayList<String>();
if(this.cell!=null){
String contents = this.cell.getContents();
if(!contents.isEmpty()){
list = StringUtils.search(this.regex, contents);
}
}
return list;
}

public String getFomatContext(){
String contents = this.cell.getContents();
//while(contents.)
return contents;
}

}




ExcelTemplate.java



package com.hna.aircrewhealth.excel.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelTemplate {
private List heads = new ArrayList();//模型表头
private List eachs = new ArrayList();//模型表数据
private List beans = new ArrayList();//一般的数据集合

}




FileTool.java



package com.hna.aircrewhealth.excel.utils;

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.net.URL;

import javax.servlet.http.HttpServletResponse;

public class FileTool {
public static File createfile(String path) {
File file = new File(path);
return file;
}

public static boolean isExist(String path) {
File file = new File(path);
return file.exists();
}

public static InputStream getFileInputStream(String path) {
try {
if (isExist(path)) {
InputStream is = new FileInputStream(path);
return is;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public static void downLoad(String filePath, HttpServletResponse response, boolean isOnLine, String newname) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + new String(newname.getBytes("gb2312"), "iso8859-1"));
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(newname.getBytes("gb2312"), "iso8859-1"));
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

public static void downLoad(InputStream f, HttpServletResponse response, String newname) throws Exception {

if (f == null) {
response.sendError(404, "File not found!");
return;
}

BufferedInputStream br = new BufferedInputStream(f);
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
// 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + newname);

OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

/**
* 在线看文件
*
* @param filePath
* @param fileType
* @param response
* @param newname
* @throws Exception
*/
public static void viewfile(String filePath, String ContentType, HttpServletResponse response, String newname) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); // 非常重要
// 在线打开方式
URL u = new URL("file:///" + filePath);
// response.setContentType(u.openConnection().getContentType());

response.setContentType(ContentType);

// response.setContentType("application/vnd.ms-excel; charset=gb2312");

response.setHeader("Content-Disposition", "inline; filename=" + new String(newname.getBytes("gb2312"), "iso8859-1"));

OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}

/**
* 把文本编码为Html代码
*
* @param target
* @return 编码后的字符串
*/
public static String htmEncode(String target) {
StringBuffer stringbuffer = new StringBuffer();
int j = target.length();
for (int i = 0; i < j; i++) {
char c = target.charAt(i);
switch (c) {
case 60:
stringbuffer.append("<");
break;
case 62:
stringbuffer.append(">");
break;
case 38:
stringbuffer.append("&");
break;
case 34:
stringbuffer.append(""");
break;
case 169:
stringbuffer.append("©");
break;
case 174:
stringbuffer.append("®");
break;
case 165:
stringbuffer.append("¥");
break;
case 8364:
stringbuffer.append("€");
break;
case 8482:
stringbuffer.append("™");
break;
case 13:
if (i < j - 1 && target.charAt(i + 1) == 10) {
stringbuffer.append("<br>");
i++;
}
break;
case 32:
if (i < j - 1 && target.charAt(i + 1) == ' ') {
stringbuffer.append("  ");
i++;
break;
}
default:
stringbuffer.append(c);
break;
}
}
return new String(stringbuffer.toString());
}

public static void main(String[] arg) {
File file = new File("F:\\js\\json_parse.js");
BakFile(file);

}

/**
* 备份一个文件
*
* @param file
*/
public static void BakFile(File file) {
if (file.isFile()) {
String filename = file.getName();
String p = file.getParent();
String newfilename = p + "\\bak." + filename;

File bakfile = createfile(newfilename);
CopyFile(file, bakfile);
}
}

public static void CopyFile(File oldFile, File newFile) {
FileInputStream input = null;
FileOutputStream output = null;
try {
input = new FileInputStream(oldFile);
output = new FileOutputStream(newFile);

byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}

}

public static void CompressJS(File file,String newname){

//        Runtime.getRuntime().exec(commandStr)
}

}




ObjectCustomUtil.java



package com.hna.aircrewhealth.excel.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ObjectCustomUtil {
public static Field[] getAllFields(Class cl) {
Field[] field = cl == null ? null : cl.getDeclaredFields();
return field;
}

public static Field getFieldByName(Class cl, String name) throws Exception {
if (name == null || name.equals(""))
return null;

Field field = cl == null ? null : cl.getDeclaredField(name);
return field;
}

/**
* 根据属性对象获取属性值
*
* @param field
* @param obj
* @return
*/
public static Object getValueByField(Field field, Object obj) {
Object result = null;
try {
String name = field.getName();
String stringLetter = name.substring(0, 1).toUpperCase();
String getName = "get" + stringLetter + name.substring(1);
Method getmethod0 = obj.getClass().getMethod(getName);
result = getmethod0.invoke(obj);

} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

/**
* 根据属性名称获取属性值
*
* @param name
* @param obj
* @return
*/
public static Object getValueByFieldName(String name, Object obj) {
Object result = null;
try {
if (obj.getClass().getName().equals(Map.class.getName()) || obj.getClass().getName().equals(HashMap.class.getName())) {
return ((Map) obj).get(name);
}
String stringLetter = name.substring(0, 1).toUpperCase();
String getName = "get" + stringLetter + name.substring(1);
Method getmethod0 = obj.getClass().getMethod(getName);
result = getmethod0.invoke(obj);

} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

/**
* 根据属性,给对象赋值
*
* @param name
* @param obj
* @return
*/
public static Object setValueByField(Field field, Object bean, Object value) {
Object result = null;
try {
String name = field.getName();
String stringLetter = name.substring(0, 1).toUpperCase();
String setName = "set" + stringLetter + name.substring(1);
Method method = bean.getClass().getMethod(setName, field.getType());
if (method != null) {
if (value.getClass().getName().equals("org.json.JSONObject$Null")) {
} else if (field.getType().getName().equals(String.class.getName())) {
method.invoke(bean, value.toString());
} else if (field.getType().getName().equals(int.class.getName()) || field.getType().getName().equals(Integer.class.getName())) {
method.invoke(bean, Integer.parseInt(StringUtils.isNull(value.toString()) ? "0" : value.toString()));
} else if (field.getType().getName().equals(float.class.getName()) || field.getType().getName().equals(Float.class.getName())) {
method.invoke(bean, Float.parseFloat(StringUtils.isNull(value.toString()) ? "0" : value.toString()));
} else if (field.getType().getName().equals(double.class.getName()) || field.getType().getName().equals(Double.class.getName())) {
method.invoke(bean, Double.parseDouble(StringUtils.isNull(value.toString()) ? "0" : value.toString()));
} else if (field.getType().getName().equals(long.class.getName()) || field.getType().getName().equals(Long.class.getName())) {
method.invoke(bean, Long.parseLong(StringUtils.isNull(value.toString()) ? "0" : value.toString()));
} else if (field.getType().getName().equals(Date.class.getName())) {
method.invoke(bean, StringUtils.isNull(value.toString()) ? null : DateTool.parse(value.toString()));
} else if (field.getType().getName().equals(BigDecimal.class.getName())) {
method.invoke(bean, StringUtils.isNull(value.toString()) ? null : BigDecimal.valueOf(Double.parseDouble(value.toString())));
} else {
method.invoke(bean, value);
}
}
return bean;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

public static String getSimpleNameByClassName(String classname) {

try {
return Class.forName(classname).getSimpleName();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public static void main(String[] arg) {
// Field[] fields = getAllFields(Aircrafttype.class);
//
// for (Field f : fields) {
// System.out.println("name=\"" + f.getName() + "\"");
// }
// Aircrafttype arg0 = new Aircrafttype();
// arg0.setAircraftModel("aaa");
// arg0.setAircrafttypeId(1234);
//
// Aircrafttype arg1 = new Aircrafttype();
// // arg1.setAircraftModel("aaa");
// arg1.setAircrafttypeId(1235);
// // arg0.getAircraftSize()
// copyNotNull(arg0, arg1);
// try {
// // System.out.println(ObjectPropertyCompare(arg0, arg1));
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}

/**
* 对象属性比较,确保两对象属于同一类型
*
* @param arg0
* @param arg1
* @return
*/
public static List<String> ObjectPropertyCompare(Object arg0, Object arg1) throws Exception {
List<String> result = null;

if (!arg0.getClass().getName().equals(arg1.getClass().getName())) {
throw new Exception("两个对象不是同一类型,没法比较");
}
Field[] fields = getAllFields(arg0.getClass());
if (fields != null && fields.length > 0)
result = new ArrayList<String>();
for (Field f : fields) {
String name = f.getName();
String stringLetter = name.substring(0, 1).toUpperCase();
String getName = "get" + stringLetter + name.substring(1);
Method method = arg0.getClass().getMethod(getName);

Object value0 = method.invoke(arg0);
Object value1 = method.invoke(arg1);

if (value0 == null && value1 == null) {
} else if (value0 == null && value1 != null) {
if (value1.getClass().getName().equals(String.class.getName())) {
if (StringUtils.isNull(value1.toString())) {
continue;
}
}
result.add(name);
} else if (value0 != null && value1 == null) {
if (value0.getClass().getName().equals(String.class.getName())) {
if (StringUtils.isNull(value0.toString())) {
continue;
}
}
result.add(name);
} else if (!value0.equals(value1))
result.add(name);
}

return result;
}

/**
* 对象属性复制(只为为空的属性复制)
*
* @param arg0
*            被复制对象
* @param arg1
*            复制原对象
* @return
*/
public static Object copyNotNull(Object arg0, Object arg1) {
// arg1.getClass().getDeclaredFields();
Field[] fields = getAllFields(arg1.getClass());

try {
for (Field f : fields) {
String typename = f.getType().getName();
Field f0 = null;
try {
f0 = arg0.getClass().getDeclaredField(f.getName());
} catch (NoSuchFieldException e) {
continue;
}
String name = f.getName();
String stringLetter = name.substring(0, 1).toUpperCase();

String getName = "get" + stringLetter + name.substring(1);
String setName = "set" + stringLetter + name.substring(1);
try {
Method setmethod1 = arg1.getClass().getMethod(setName, f.getType());
Method getmethod1 = arg1.getClass().getMethod(getName);

Method getmethod0 = arg0.getClass().getMethod(getName);

if (typename.equals(int.class.getName()) || typename.equals(Integer.class.getName()) || typename.equals(float.class.getName()) || typename.equals(Float.class.getName()) || typename.equals(double.class.getName()) || typename.equals(Double.class.getName())) {

if (getmethod1.invoke(arg1).equals(0) && f0 != null && f.getType().getName().equals(f0.getType().getName())) {
setmethod1.invoke(arg1, getmethod0.invoke(arg0));
}
} else if (getmethod1.invoke(arg1) == null) {
if (f0 != null && f.getType().getName().equals(f0.getType().getName())) {
setmethod1.invoke(arg1, getmethod0.invoke(arg0));
}
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// System.out.println("");

return arg1;
}
}




StringUtils.java



package com.hna.aircrewhealth.excel.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
/**
* 查找一个字符串在数组中的索引值
*
* @param data
* @param string
* @return
*/
public static int searchIndex(String[] data, String string) {
if (data == null || data.length == 0)
return -1;
for (int i = 0; i < data.length; i++) {
if ((data[i] != null && data[i].equals(string)) || (data[i] == null && string == null)) {
return i;
}
}
return -1;
}

public static boolean isNull(String string) {
if (string == null || string.equals(""))
return true;
return false;
}

public static String arrayToString(List<String> list, String split) {
if (list == null || list.size() == 0)
return null;

String result = "";
if (isNull(split))
split = ",";

for (String str : list) {
result += str + split;
}
result = result.substring(0, result.length() - 1);
return result;
}

public static String arrayToString(String[] list, String split) {
if (list == null || list.length == 0)
return null;

String result = "";
if (isNull(split))
split = ",";

for (String str : list) {
result += str + split;
}
result = result.substring(0, result.length() - 1);
return result;
}

public static String getFileName(String name) {
if (isNull(name))
return null;

if (name.lastIndexOf("\\") != -1) {
name = name.substring(name.lastIndexOf("\\") + 1, name.length());
} else if (name.lastIndexOf("/") != -1) {
name = name.substring(name.lastIndexOf("/") + 1, name.length());
}

return name;
}

public static String getExtensionName(String name) {
if (isNull(name))
return null;
if (name.lastIndexOf(".") != -1) {
return name.substring(name.lastIndexOf(".") + 1);
}
return "";
}

public static void main(String[] arg0) {
String a = "${bean.aid} sdfad ${xx.yy}sfdd";

String regex = "";

search(regex, a);
}

public static String getUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}

/**
* 查找【正则表达式】描述的内容。
* @param regex
* @param string
* @return
*/
public static List<String> search(String regex, String string) {
List<String> list = new ArrayList<String>();
Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(string);
while (m.find()) {
String g = m.group();
list.add(g);
}
return list;
}
}




代码贴完了,至于下载

下面是我自己写的可以参照 一下,Excel生成并下载

ccAction.java 方法



@RequestMapping(params = "method=InitExport", method = RequestMethod.GET)
public @ResponseBody String InitExport(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, JSONException{
String parameter=URLDecoder.decode(request.getParameter("parameter"),"UTF-8");
JSONObject jsonObj=new JSONObject(parameter);
Map<String,Object> map=new HashMap<String,Object>();
String path = request.getSession().getServletContext().getRealPath("/")+ "ExcelTemplate" +"\\招飞初检.xls";
Physical physical=new Physical();
physical.setCompany(jsonObj.get("company").toString());
physical.setDateTimes(jsonObj.get("dateTime").toString());
//        String area= hnabaseCityBO.findoneById(jsonObj.get("area").toString()).getBaseChn();
physical.setArea(jsonObj.optString("area"));//
physical.setRealNumber(jsonObj.get("realNumber").toString());
physical.setPassNumber(jsonObj.get("passNumber").toString());
physical.setEndYield(jsonObj.get("endYield").toString());
physical.setDoctors(jsonObj.get("doctorInit").toString());//
physical.setComment(jsonObj.get("comment").toString());
map.put("physical", physical);
//        ExcelTool.exportExcel(path, map);
OutputStream out=null;
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
InputStream in=null;
try{
in=ExcelTool.exportExcel(path, map);
bis=new BufferedInputStream(in);
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("招飞初检.xls", "UTF-8"));//设置头文件  可参照 http://blog.csdn.net/fanyuna/article/details/5568089
byte[] data=new byte[1024];
int bytes=0;
out=response.getOutputStream();
bos=new BufferedOutputStream(out);
while((bytes=bis.read(data, 0, data.length))!=-1){
bos.write(data,0,bytes);                                        //写出文件流
}
bos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
bos.close();
out.close();
bis.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}

}
return "success";

}




其中有一个循环的,下面代码也给出来吧



each代表循环

完整实例和Excel模板下载地址:http://download.csdn.net/detail/dawnsun2013/6723789

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: