php 或者js 从数据库表导出excel已查询出的单行数据导出到excel,点击后实现导出放置到指定位置?

JSP数据导出到EXCEL简便方法-JSP技巧
JSP数据导出到EXCEL简便方法
发表日期:
试试看从网页中把表格直接生成,虽然不是直接从到excel,不过反而更加方便而且人性化。。网上倒是找到了不少的资料,发现一段scrt的功能实现代码,很不错:var elTable = document.getElementById(&tb&); var oRangeRef = document.body.createTextRange(); oRangeRef.moveToElementText( elTable ); oRangeRef.execCommand( &Copy& );var appExcel = new ActiveXObject( &Excel.& ); appExcel.Visible = appExcel.Workbooks.Add().Worksheets.Item(1).Paste(); appExcel =实现功能就是把id为tb的表格内的都生成为excel,我试试了可行,但是放到服务器来运行就是script error的提示,然后网上到处求问,也找了百度空间的几位高手朋友问了下,可是还是不得其法。。不过还是很感谢他们的热心帮助没办法,我只能用别的方法来实现了,其实满喜欢上面的这个的功能的,比较人性化。。可惜我黔驴技穷,无法用上它,哎!~既然我帮客户用写的程序,那么我就还是用jsp来实现这个功能吧。。于是找到了这么一个方法:原文出自:***************************************************************************************************一、将网页资料以excel报表以线上浏览方式呈现 xls651.jsp原始码如下&%@ page contentType=&application/msexcel& %&&!-- 以上这行设定本网页为excel格式的网页 --&&%
response.setHeader(&Content-disposition&,& filename=test1.xls&);
//以上这行设定传送到前端浏览器时的档名为test1.xls
//就是靠这一行,让前端浏览器以为接收到一个excel档 %&&html&&head&&title&Excel档案呈现方式&/title&&/head&&body&
&table border=&1& width=&100%&&
&td&姓名&/td&&td&身份证字号&/td&&td&生日&/td&
&td&李玟&/td&&td&N&/td&&td&&/td&
&td&梁静如&/td&&td&N&/td&&td&&/td&
&td&张惠妹&/td&&td&N&/td&&td&&/td&
&/table&&/body&&/html&二、将网页资料以excel报表以下载的方式呈现这个档和上一个差不多,只有差别在这一行:线上浏览的方式: response.setHeader(&Content-disposition&,& filename=test1.xls&); 下载的方式: response.setHeader(&Content-disposition&,& filename=test2.xls&); 附注: 1.以上纯以静态网页的方式呈现档,配合资料库,你便能以动态的报表方式做出excel报表了2.完全不用安装任何元件,或只能受限於win平台,一个简单的方式解决你的需求 3.聪明的你,应该能举一反三,知道如何将网页资料以的doc格式展现了吧!(是不是只要把contentType改成&application/msword&以及filename的副档名改成.doc就可以了!)x
(人气:12489)
┃&猜你喜欢
┃&教程搜索服务
┃&本月文章推荐
┃&项目外包信息
┃&网络编程文章分类
站长工具:
实用工具:下次自动登录
现在的位置:
& 综合 & 正文
phpexcel 读取含多个sheet的excel,将从数据库中检索出的数据分别写入该excel不同的sheet中 并导出该excel
下载phpexcel类库,解压将Class文件夹放入项目中。
header("Content-Type:text/
charset=utf-8");
header("Cache-Control:no-cache");
require_once("/lib/phpmailer/class.phpmailer.php");
require_once("/lib/phpmailer/class.smtp.php");
require_once 'Classes/PHPExcel.php';
require_once 'Classes\PHPExcel\Reader\Excel5.php';
require_once 'Classes/PHPExcel/Writer/Excel2007.php';
require_once 'Classes/PHPExcel/Writer/Excel5.php';
include_once 'Classes/PHPExcel/IOFactory.php';
//连接数据库,自己填入连接内容,这里连接的是mysql
$dbuser="";
$dbpwd="";
$dbhost="";
$dbdatabase="";
$db=mysql_connect($dbhost,$dbuser,$dbpwd);
mysql_query("set names 'gbk'");//这就是指定数据库字符集,一般放在连接数据库后面就行了(非常重要)
mysql_select_db($dbdatabase,$db);
//读取已设置好的excel
$objPHPExcel = PHPExcel_IOFactory::load("excel_mode/dept.xls");//修改为自己的excel路径
//这里将数据写入第三个sheet中,每个sheet都设置值,则分别设置
$currentSheet1=$objPHPExcel-&getSheet(2);
$mysql_net="select
n.id as '编号',
n.otherserial as '固定资产编号',
l.completename as '部门',
nt.name as '类型',
nm.name as '型号',
n.name as '名称',
m.name as '制造商',
n.comment as '批注',
u.realname as '用户',
u.firstname as '工号'
from glpi_networkequipments n
left join glpi_users u on u.id=n.users_id
left join glpi_locations l on n.locations_id=l.id
left join glpi_manufacturers m on n.manufacturers_id=m.id
left join glpi_networkequipmenttypes nt on n.networkequipmenttypes_id=nt.id
left join glpi_networkequipmentmodels nm on n.networkequipmentmodels_id=nm.id
where n.is_deleted=0
and n.locations_id='".$arr[5]."'
group by n.otherserial
$myresult_net=mysql_query($mysql_net,$db);
while($arr_net=mysql_fetch_array($myresult_net))
/*----------从数据库读取数据--------------------*/
$number_net=$j_net++;
$name_net=$arr_net[1];
$username_net=$arr_net[8];
$gonghao_net=$arr_net[9];
$deptment_net=$arr_net[2];
$leixing_net=$arr_net[3];
$xinghao_net=$arr_net[4];
$netname_net=$arr_net[5];
$make_net=$arr_net[6];
/*-----------转码-----------*/
$name_net=iconv("gbk","utf-8", $name_net);
$username_net=iconv("gbk","utf-8", $username_net);
$gonghao_net=iconv("gbk","utf-8", $gonghao_net);
$deptment_net=iconv("gbk","utf-8", $deptment_net);
$leixing_net=iconv("gbk","utf-8", $leixing_net);
$xinghao_net=iconv("gbk","utf-8", $xinghao_net);
$netname_net=iconv("gbk","utf-8", $netname_net);
$make_net=iconv("gbk","utf-8", $make_net);
$u1_net=$i_net+3;
/*----------写入内容-------------*/
$currentSheet1-&getCell('a'.$u1_net)-&setValue("$number_net");
$currentSheet1-&getCell('b'.$u1_net)-&setValue("$name_net");
$currentSheet1-&getCell('c'.$u1_net)-&setValue("$username_net $gonghao_net");
$currentSheet1-&getCell('d'.$u1_net)-&setValue("$deptment_net");
$currentSheet1-&getCell('e'.$u1_net)-&setValue("$leixing_net");
$currentSheet1-&getCell('f'.$u1_net)-&setValue("$xinghao_net");
$currentSheet1-&getCell('g'.$u1_net)-&setValue("$netname_net");
$currentSheet1-&getCell('h'.$u1_net)-&setValue("$make_net");
//设置第一个sheet中A5的值为“hello world”
$currentSheet2=$objPHPExcel-&getSheet(0);
$currentSheet2-&getCell('A5')-&setValue("hello world");
//写入到文件
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$outputFileName = "excel/dept.xls";//自行设置路径
$objWriter-&save($outputFileName);
&&&&推荐文章:
【上篇】【下篇】java 导出数据到指定的excel模板中。
编辑:www.fx114.net
本篇文章主要介绍了"java 导出数据到指定的excel模板中。",主要涉及到java 导出数据到指定的excel模板中。方面的内容,对于java 导出数据到指定的excel模板中。感兴趣的同学可以参考一下。
为什么这样写呢,因为这样写方便修改,不会出太多的乱子!直奔主题:
使用的JXL包
EXCEL样式:
页面样式:
网页页面链接:
location.href = &physical.do?method=InitDownLoad&downLoadPath=&+ encodeURIComponent(encodeURIComponent(downLoadPath));
location.href是打开窗口并自动下载,这个很重要
下面是后台代码:
后台代码分了七个类,有6是公共方法为一个类服务,我贴顺序是主要,次要。。。。。
ExcelTool.java
package com.hna.aircrewhealth.excel.
import java.io.F
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.IOE
import java.io.InputS
import java.lang.reflect.F
import java.util.ArrayL
import java.util.D
import java.util.HashM
import java.util.I
import java.util.LinkedHashM
import java.util.L
import java.util.M
import com.hna.aircrewhealth.po.AviatorHealthC
import com.hna.aircrewhealth.security.po.S
import jxl.C
import jxl.S
import jxl.W
import jxl.read.biff.BiffE
import jxl.write.DateT
import jxl.write.L
import jxl.write.N
import jxl.write.WritableC
import jxl.write.WritableW
import jxl.write.WriteE
public class ExcelTool {
private static String path = &F:\\luokq\\aircrewhealth\\template\\重大疾病报告单.xls&;
private final static String defaultName = &航医跟班检查记录单.xls&;
public static String getPath() {
public static void setPath(String 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(&&);
bean.setEndTime(&&);
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(&&+&----&+i);
bean.setEndTime(&&+&----&+i);
bean.setFollowContext(&脸可大饿,打瞌睡,而开发,奥东科咳咳咳什么刺激附近的库斯科到看风景的库斯科,道可服务端&+&----&+i);
list.add(bean);
map.put(&listname&, list);
map.put(&listname2&, list);
/**这是循环结束了*/
exportExcel(path, map);
//这个最主要,是导出Excel的方法
* 导出 Excel
* @param template
* @param datas
public static FileInputStream exportExcel(String template, Map&String, Object& datas) {
FileInputStream fis = null;
InputStream is = FileTool.getFileInputStream(template);
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){
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public static FileInputStream exportExcel1(String template, Map&String, Object& datas) {
FileInputStream fis = null;
InputStream is = FileTool.getFileInputStream(template);
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){
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
* 处理【表达式】类型的数据。
* @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 = sheetI
int startRow = list.get(0).getCell().getRow() +// 获取开始行下标。
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&)
// 有数据时。
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()));
/* 创建新行 */
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++;
// 无数据时。
for (ExcelCells cell : list) {
wWorkbook.getSheet(sheetIndex).addCell(getValueByEach(cell, null, startRow, cell.getCell().getColumn()));
* 根据【表达式】从数据集中获取相应数据。
* @param exp
* @param datas
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);
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 writableC
* 这个方法是专门用于驻外机组环境卫生检查
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);
object = ObjectCustomUtil.getValueByFieldName(name, object);
if(name.indexOf(&checkContent&)!=-1){
if(&0&.equals(object.toString())){
checkContentValue = &符合&;
}else if(&1&.equals(object.toString())){
checkContentValue = &不符合&;
checkContentValue = &未检查&;
}else if(name.indexOf(&checkTime&)!=-1){
Date date = (Date)
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());
old_c = old_c.replace(exp, checkContentValue);
writableCell = getWritableCellByObject(cells.getCell().getRow(), cells.getCell().getColumn(), old_c);
writableCell.setCellFormat(cells.getCell().getCellFormat());
return writableC
* 根据【Each表达式】从数据集中获取相应数据。
* @param exp
* @param datas
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. i++) {
if (object == null)
object = ObjectCustomUtil.getValueByFieldName(exps[i], datas);
object = ObjectCustomUtil.getValueByFieldName(exps[i], object);
writableCell = getWritableCellByObject(rows, column, object);
writableCell = getWritableCellByObject(rows, column, null);
writableCell.setCellFormat(cells.getCell().getCellFormat());
return writableC
* 【未实现】
* @param beginRow
* @param beginColumn
* @param heads
* @param result
public static synchronized String customExportExcel(int beginRow, int beginColumn, Map heads, List result) {
return null;
* 根据提供的【列标】、【行标】、【对象值】构建一个Excel列对象。
* @param beginRow
* @param beginColumn
* @param obj
【对象值】
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);
cell = new Label(beginColumn, beginRow, obj.toString());
* 查找某字符第一次出现的位置。
* @param text
* @param book
【Excel对象】
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 & 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++;
* 查找包含某字符所有的列对象。
* @param text
* @param book
【Excel对象】
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 & 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));
DateTool.java
package com.hna.aircrewhealth.excel.
import java.text.DateF
import java.text.ParseE
import java.text.SimpleDateF
import java.util.C
import java.util.D
public class DateTool {
public static Date parse(String string) {
DateFormat format = DateFormat.getDateInstance();
return format.parse(string);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
* 获取当前日期时间
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;
* 获取当天日期(短日期)
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);
* 获取当天日期(长日期)
public static String getTodayDateLong() {
Date sellTime = new Date();
SimpleDateFormat dateformat1 = new SimpleDateFormat(&yyyy-MM-dd HH:mm:ss&);
return dateformat1.format(sellTime);
* 获取当前年份
* @author zl
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 + & 月&);
* 将日期格式化
* @param date
* @param arg
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);
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();
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;如:.&);
//计算当前距离当前日期之后的某个日期
public static String addCalendarDay(Date calDate, long addDate) {
long time = calDate.getTime();
addDate = addDate * 24 * 60 * 60 * 1000;
time += addD
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 += addD
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 -= addD
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();
//System.out.println(DateTool.stringToDate(&&));
Date date=new Date();
System.out.println(DateTool.addCalendarDay(date,1));
//System.out.println(DateTool.countDays(&&,&&));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
日期类型的转换哈
ExcelCells.java
package com.hna.aircrewhealth.excel.
import java.util.ArrayL
import java.util.L
import jxl.C
import jxl.S
public class ExcelCells {
public final static String regex = &\\$\\{[^\\}]+\\}&;
private int sheetI
public ExcelCells(){}
public ExcelCells(Sheet sheet,Cell cell){
this.sheet =
this.cell =
public ExcelCells(Sheet sheet,Cell cell,int sheetIndex){
this.sheet =
this.cell =
this.sheetIndex = sheetI
public Sheet getSheet() {
public void setSheet(Sheet sheet) {
this.sheet =
public Cell getCell() {
public void setCell(Cell cell) {
this.cell =
public int getSheetIndex() {
return sheetI
public void setSheetIndex(int sheetIndex) {
this.sheetIndex = sheetI
* 获取当前列当中【表达式】集合
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);
public String getFomatContext(){
String contents = this.cell.getContents();
//while(contents.)
ExcelTemplate.java
package com.hna.aircrewhealth.excel.
import java.util.ArrayL
import java.util.HashM
import java.util.L
import java.util.M
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.
import java.io.BufferedInputS
import java.io.F
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.FileOutputS
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.net.URL;
import javax.servlet.http.HttpServletR
public class FileTool {
public static File createfile(String path) {
File file = new File(path);
public static boolean isExist(String path) {
File file = new File(path);
return file.exists();
public static InputStream getFileInputStream(String path) {
if (isExist(path)) {
InputStream is = new FileInputStream(path);
} 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!&);
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&, & filename=& + new String(newname.getBytes(&gb2312&), &iso8859-1&));
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType(&application/x-msdownload&);
response.setHeader(&Content-Disposition&, & 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!&);
BufferedInputStream br = new BufferedInputStream(f);
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
// 纯下载方式
response.setContentType(&application/x-msdownload&);
response.setHeader(&Content-Disposition&, & 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!&);
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- charset=gb2312&);
response.setHeader(&Content-Disposition&, & 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 & i++) {
char c = target.charAt(i);
switch (c) {
stringbuffer.append(&&&);
stringbuffer.append(&&&);
stringbuffer.append(&&&);
stringbuffer.append(&&&);
stringbuffer.append(&&&);
stringbuffer.append(&&&);
stringbuffer.append(&&&);
case 8364:
stringbuffer.append(&&&);
case 8482:
stringbuffer.append(&™&);
if (i & j - 1 && target.charAt(i + 1) == 10) {
stringbuffer.append(&&br&&);
i++;
if (i & j - 1 && target.charAt(i + 1) == ' ') {
stringbuffer.append(& &&);
i++;
stringbuffer.append(c);
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.& +
File bakfile = createfile(newfilename);
CopyFile(file, bakfile);
public static void CopyFile(File oldFile, File newFile) {
FileInputStream input = null;
FileOutputStream output = null;
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 {
if (input != null) {
input.close();
if (output != null) {
output.close();
} catch (IOException ioe) {
public static void CompressJS(File file,String newname){
Runtime.getRuntime().exec(commandStr)
ObjectCustomUtil.java
package com.hna.aircrewhealth.excel.
import java.lang.reflect.F
import java.lang.reflect.InvocationTargetE
import java.lang.reflect.M
import java.math.BigD
import java.util.ArrayL
import java.util.D
import java.util.HashM
import java.util.L
import java.util.M
public class ObjectCustomUtil {
public static Field[] getAllFields(Class cl) {
Field[] field = cl == null ? null : cl.getDeclaredFields();
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);
* 根据属性对象获取属性值
* @param field
* @param obj
public static Object getValueByField(Field field, Object obj) {
Object result = null;
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();
* 根据属性名称获取属性值
* @param name
* @param obj
public static Object getValueByFieldName(String name, Object obj) {
Object result = null;
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();
* 根据属性,给对象赋值
* @param name
* @param obj
public static Object setValueByField(Field field, Object bean, Object value) {
Object result = null;
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())));
method.invoke(bean, value);
} 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();
public static String getSimpleNameByClassName(String classname) {
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);
// // System.out.println(ObjectPropertyCompare(arg0, arg1));
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
* 对象属性比较,确保两对象属于同一类型
* @param arg0
* @param arg1
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())) {
result.add(name);
} else if (value0 != null && value1 == null) {
if (value0.getClass().getName().equals(String.class.getName())) {
if (StringUtils.isNull(value0.toString())) {
result.add(name);
} else if (!value0.equals(value1))
result.add(name);
* 对象属性复制(只为为空的属性复制)
* @param arg0
被复制对象
* @param arg1
复制原对象
public static Object copyNotNull(Object arg0, Object arg1) {
// arg1.getClass().getDeclaredFields();
Field[] fields = getAllFields(arg1.getClass());
for (Field f : fields) {
String typename = f.getType().getName();
Field f0 = null;
f0 = arg0.getClass().getDeclaredField(f.getName());
} catch (NoSuchFieldException e) {
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);
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.
import java.util.ArrayL
import java.util.L
import java.util.UUID;
import java.util.regex.M
import java.util.regex.P
public class StringUtils {
* 查找一个字符串在数组中的索引值
* @param data
* @param string
public static int searchIndex(String[] data, String string) {
if (data == null || data.length == 0)
return -1;
for (int i = 0; i & data. i++) {
if ((data[i] != null && data[i].equals(string)) || (data[i] == null && string == null)) {
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 +
result = result.substring(0, result.length() - 1);
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 +
result = result.substring(0, result.length() - 1);
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());
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
public static List&String& search(String regex, String string) {
List&String& list = new ArrayList&String&();
Pattern p = pile(regex);
Matcher m = p.matcher(string);
while (m.find()) {
String g = m.group();
list.add(g);
代码贴完了,至于下载
下面是我自己写的可以参照 一下,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;
in=ExcelTool.exportExcel(path, map);
bis=new BufferedInputStream(in);
response.setHeader(&Content-Disposition&, &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();
bos.close();
out.close();
bis.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
return &success&;
其中有一个循环的,下面代码也给出来吧
&each代表循环
完整实例和Excel模板下载地址:http://download.csdn.net/detail/dawnsun
本文标题:
本页链接:

我要回帖

更多关于 数据库导出到excel 的文章

 

随机推荐