导航:首页 > 编程语言 > java导出excel报表

java导出excel报表

发布时间:2023-02-09 17:40:38

java中怎么样导出表到excel中

如果是JSP页面要导出成excel,依靠javascript就可以实现了,具体你试试上面的代码 <input type="button" value="保存为 Excel"> <script language="javascript">
function AllAreaExcel() {
var title; title=document.getElementsByTagName("table")[0].childNodes.item(0).childNodes(0).childNodes(0).innerText; alert(title); var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;

//从excel的第5行开始插入
oSheet.Range("A5").select;

oWB .Worksheets(1).Activate;
oSheet.Cells(3,1).Value=title; //在第3行插入报表头
oWB.Worksheets(1).Range("A3:I3").merge(); // 合并单元格区域 A3:I3
oWB.Worksheets(1).Range("A3:I3").HorizontalAlignment=3; //居中对齐A3:I3
var sel=document.body.createTextRange();
sel.moveToElementText(table1); //table 的ID值
sel.select();
sel.execCommand("Copy");
oSheet.Paste();

oXL.Visible = true;
} </script>

⑵ java将数据导出excel计算其文件大小

热门频道

首页

博客

研修院

VIP

APP

问答

下载

社区
推荐频道

活动

招聘

专题
打开CSDN APP
Copyright © 1999-2020, CSDN.NET, All Rights Reserved

打开APP

大数据导出excel大小限制_java 导出Excel 大数据量,自己经验总结! 原创
2020-12-19 01:58:16

weixin_39655377
码龄5年
关注
分析导出实现代码,XLSX支持:

/*** 生成XLSX,2007版本的excel,每个sheet无6.5W的行数限制,但是到了一定数量,可能内存溢出,

* 次方法适合在预计10W以下的数据导出时使用,本机测试,14W可以导出。列数量在8列左右

*

*@paramfileOut

* 输出流

*@paramsheetMap

* 要设置的数据信息

*@throwsSQLException*/

public static voidcreateXSLXByResultSet(OutputStream fileOut, WriteXLSBean... beans)throwsSQLException {try{//重点 Workbook

Workbook wb = newXSSFWorkbook();for (int i = 0, len = beans.length; i < len; i++) {

WriteXLSBean xlsBean=beans[i];

Sheet sheet=wb.createSheet(xlsBean.getSheetName());

ResultSet rs=xlsBean.getRs();

ResultSetMetaData rsmd=rs.getMetaData();

TypeHandlerRegistry tr=BeanContext.tr;

Map th =xlsBean.getTh();int index = 0;while(rs.next()) {long t1 =System.currentTimeMillis();

org.apache.poi.ss.usermodel.Row row=sheet

.createRow(index);for (int j = 0, numberOfColumns = rsmd.getColumnCount(); j < numberOfColumns; j++) {

String key= rsmd.getColumnLabel(j + 1).toLowerCase();if(th.containsKey(key)) {

TypeHandler> type =tr.getTypeHandler(JdbcType

.forCode(rsmd.getColumnType(j+ 1)));

Object obj=type.getResult(rs, key);

row.createCell(j).setCellValue(obj== null ? "": obj.toString());

}

}

System.out.println(index+ " :"

+ (System.currentTimeMillis() -t1));

index++;

}

}//重点 Workbook

wb.write(fileOut);

}catch(IOException e) {

e.printStackTrace();throw new ServiceRunTimeException("生产xls文档错误", e);

}finally{

}

}

在上面 标注了重点的两处,分别是:

1.构建一个Excel对象

2.将该对象写入一个OutPutStream

而在构建过程中,没有地方写入OutPutSteam ,也就是说必须在内存中构建整个 Excel,才能进行写出操作,在大数据量情况下,这样将导致所有数据加载到内存中,而不能输出,导致最后 内存溢出。

根据运行环境不用,可能内存溢出的 情况不同

根据情况,如果数据量达到10W以上,建议使用

1、多个Excel,每个Excel一个Sheet,因为所有Sheet都是Workbook的组成部分。如果不分多个Excel,即使分Sheet也没用,

2、每个Excel中列数适中,比如: 5W行每个Excel档,实现分多次导出和分页查询原理一样

3、对多个Excel导出到一个临时目录,并通过程序压缩,然后提供给客户下载

2003版通过数据库结果存到List中,然后进行生产:Table 就是List Row 是Map

/*** 生产xls,2003版本的excel,每个sheet有6.5W的行数限制

*

*@paramfileOut

* 输出流,未关闭

*@paramsheetMap

* 要导出的数据信息*/

public static void createXSLByMap(OutputStream fileOut, Map>>sheetMap) {try{

HSSFWorkbook wb= newHSSFWorkbook();

Set keys =sheetMap.keySet();for (Iterator iterator =keys.iterator(); iterator

.hasNext();) {

String SheetKey=iterator.next();

Sheet sheet=wb.createSheet(SheetKey);

List> sheetRows =sheetMap.get(SheetKey);for (int i = 0, len = sheetRows.size(); i < len; i++) {

Map cellMap =sheetRows.get(i);

Set cellSet =cellMap.keySet();

org.apache.poi.ss.usermodel.Row row=sheet.createRow(i);int j = 0;for (Iterator iterCell =cellSet.iterator(); iterCell

.hasNext(); j++) {

String cellKey=iterCell.next();

Object obj=cellMap.get(cellKey);

row.createCell(j).setCellValue(obj== null ? "": obj.toString());

}

}

}

wb.write(fileOut);

}catch(IOException e) {

e.printStackTrace();throw new ServiceRunTimeException("生产xls文档错误", e);

}finally{

}

}

新版本 POI+office 2007版本excel可以导出几十万条而不内存溢出,详细见:

导出大量数据到 excel 的 xlsx文件

static String src="SFGHJKJGHFERTUIO";

public static void main(String[] args) throwsThrowable {

SXSSFWorkbook wb = new SXSSFWorkbook(100); //这里100是在内存中的数量,如果大于此数量时,会写到硬盘,以避免在内存导致内存溢出

Sheet sh =wb.createSheet();

for (int rownum = 0; rownum < 1000000; rownum++) {

Row row =sh.createRow(rownum);

for (int cellnum = 0; cellnum < 10; cellnum++) {

Cell cell =row.createCell(cellnum);

String address = newCellReference(cell).formatAsString();

cell.setCellValue(address+src.substring(rownum%10*10+1, (rownum%10+1)*10));

}

}

File file = new File("F:/aa.xlsx");

file.createNewFile();

FileOutputStream out = newFileOutputStream(file);

wb.write(out);

out.close();

}

内存使用情况:

根据以上前辈经验,自己在结果自身需求考虑,整合出一个工具。解决了excle表.xls格式行数65535行的限制。我实现的形式是导出一张表,里面有多页

(我是已65000为一页)

这里是用反射来使用所有传入进行的实体的属性的值。这里只针对String和基本数据类型。如有自己定义的类型需要自己加上。

packagecom.tommy.fundation.util;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.ArrayList;importjava.util.Date;importjava.util.List;public classRelectUtil {public static List reflectEntity(T model,Class> cals) throwsNoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchFieldException{

List list = new ArrayList();

Field[] field= model.getClass().getDeclaredFields(); //获取实体类的所有属性,返回Field数组

for(int j=0 ; j

String nam = field[j].getName(); //获取属性的名字

String name =nam;

name= name.substring(0,1).toUpperCase()+name.substring(1);

String type= field[j].getGenericType().toString(); //获取属性的类型

if(type.equals("class java.lang.String")){ //如果type是类类型,则前面包含"class ",后面跟类名

Method m = model.getClass().getMethod("get"+name);

String value= (String) m.invoke(model); //调用getter方法获取属性值

if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Integer")){

Method m= model.getClass().getMethod("get"+name);

Integer value=(Integer) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Short")){

Method m= model.getClass().getMethod("get"+name);

Short value=(Short) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Double")){

Method m= model.getClass().getMethod("get"+name);

Double value=(Double) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.lang.Boolean")){

Method m= model.getClass().getMethod("get"+name);

Boolean value=(Boolean) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}if(type.equals("class java.util.Date")){

Method m= model.getClass().getMethod("get"+name);

Date value=(Date) m.invoke(model);if(value != null){

list.add(value);

}else{

list.add("");

}

}

}returnlist;

}

}

下面将是重点实现导出excel表

packagecom.tommy.fundation.util;importjava.io.OutputStream;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importjavax.servlet.http.HttpServletResponse;importorg.apache.poi.hssf.record.formula.functions.T;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;

@SuppressWarnings("hiding")public class ExportExcel{/*** 导出多张excel表,解决xls格式行数65535的限制

*@authorOnlyOne

*@paramresponse

*@paramlist 需要处理的list数据集合

*@throwsException*/@SuppressWarnings("deprecation")public void doExcel(HttpServletResponse response,List list,String fileName) throwsException {

OutputStream os= response.getOutputStream();//获取输出流

response.reset();//设置下载头部信息。Content-disposition为属性名。attachment表示以附件方式下载,如果要在页面中打开,则改为inline。filename为文件名

response.setHeader("Content-disposition", "attachment; filename=excell.xls");

response.setContentType("application/msexcel");

Map> sheetMap =daData(list);

HSSFWorkbook wb= newHSSFWorkbook();

Set keys =sheetMap.keySet();for (Iterator iterator =keys.iterator(); iterator.hasNext();) {

Integer SheetKey=iterator.next();

HSSFSheet sheet= wb.createSheet((fileName+SheetKey).toString());

List sheetRows =sheetMap.get(SheetKey);for (int i = 0, len = sheetRows.size(); i < len; i++) {

T en=(T) sheetRows.get(i);

List dataList = RelectUtil.reflectEntity(en, en.getClass());

HSSFRow row=sheet.createRow(i);

row.createCell(0).setCellValue(String.valueOf(i));for(int m=0; m

row.createCell(m+1).setCellValue(dataList.get(m).toString());

}

}

}

wb.write(os);

}/*** 此方法将数据集合按65000个进行分割成多个子集合

*@authorOnlyOne

*@paramlist 需要处理的list数据集合

*@return

*/

public Map> daData(Listlist){int count = list.size()/65000;int yu = list.size() % 65000;

Map> map = new HashMap>();for (int i = 0; i <= count; i++) {

List subList = new ArrayList();if (i ==count) {

subList= list.subList(i * 65000, 65000 * i +yu);

}else{

subList= list.subList(i * 65000, 65000 * (i + 1)-1);

}

map.put(i, subList);

}returnmap;

}

}

在Java中调用的方式

@RequestMapping(value = "/doExcel", method =RequestMethod.GET)public void doExcel(HttpServletResponse response,HttpServletRequest request) throwsException {

List list =enrolltgService.findAll();new ExportExcel().doExcel(response, list, "黑白淡奶");

}

大功搞成,以后再也不会为了数据量太大而导不出来烦恼了!!!

需要的包 poi-3.2-FINAL-20081019.jar

相关资源:poi读取大文件Excel,使用xml格式解析,速度实测50mb文件13s,可指定...
打开CSDN,阅读体验更佳

POI多线程分表导出百万级大数据量EXCEL导出_Zhuo_chao的博客-CSDN博 ...
由上面可知 Excel 2003及以下是无法实现单sheet百万级的数据。 ApachePOI 简介 Apache POI 是用Java编写的免费开源的跨平台的 JavaAPI,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功...
Java 使用POI导出数据到 excel,单 sheet 和多 sheet__修铁路的的博客...
单sheet 和多 sheet,用到的jar都是一样的,无非就是多创建一个 sheet的问题,以下是需要用到的jar包,在对应模块的pom.xml 中引入即可 <dependency> <groupId>org.apache.poi</groupId> ...
java导出excel超出65533行
业务背景: 列表导出,数据导出超过65533行 解决方案: 1、超出65533行,直接系统提示:本系统支持导出的最大条数为65533行 2、导出模版改为.xlsx,POI导出时用XSSFWorkbook,把所有数据都拿到内存里,可以导出超过65533行,但是上线之后,发现会内存溢出 3、导出模版改为.xlsx,POI导出时用SXSSFWorkbook,每次往内存里放一定的数据,导完之后,刷新,再次...
继续访问
Java的poi导出的excel不能超过256列的解决办法
Java的poi导出的excel不能超过256列的解决办法背景1、现在的情况2、解决办法 背景 1、现在的情况 excel文件名以.xls结尾 这个构造函数中默认采取这个类型 this.type = ExcelType.HSSF; public ExportParams(String title, String sheetName) { this.color = HSSFColorPredefined.WHITE.getIndex(); this.headerColor = HSSFC
继续访问
使用ApachePOI导出excel(多个sheet页)_我是橘子京的博客
2、设置导出excel路径 //导出的文件路径 String filePath="D:\\excel.xls"; 1 2 3、创建excel文件 //创建Excel文件(Workbook) HSSFWorkbook workbook = new HSSFWorkbook(); 1 2 4、设置单元格样式 //设置单元格样式 HSSFCel...
POI3.8 导出大数据excel(50万左右)_咖啡加糖_的博客_poi支持最...
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.streaming.SXSSFWorkbook; ...
最新发布 【JAVA问题解决方案】01.EasyExcel导出数据超过Excel单表上限解决方案
1.了解一下Excel单表最多存储多少行数据(可以存储1048576条数据,1024的平方,2的20次方)。本文是介绍EasyExcel导出数据超过Excel单表上限解决方案。2.知道最多多少行就能以这个数为条件,如果超过则进行分表。3.分表的同时需要对数据进行分割,才能不超过最大限度。实体类(非常简单,为了导出表更快)
继续访问

java实现流输出形式导出数据(使用EasyExcel)并打包为zip包
java实现流输出形式文件下载并打包为zip包 pom.xml文件导入easyexcel <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.0.5</version> </d...
继续访问
...到excel文件(xls格式),附实验结果(单张sheet最多可有65536行)& Fi...
使用POI导出MySQL数据库数据到excel文件(xls格式) 注意事项:单张sheet最多存储65536行!否则报错! Caused by: java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535) !
使用Apache POI导出百万条EXCEL数据_橙乐果果的博客
工作中,有这么一个需求:每天凌晨00:05分定时从数据库导出大于三个月的订单流水信息,保存为excel文件。 Just do it. 1.引入POM依赖 <!-- excel --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> ...
Linux下读写文件操作
Linux下读写文件操作 #include<stdio.h> typedef struct Student { int no; char name[10]; int score; }Student; int main(int args,char *argv[]) { //打开文件 FILE *fp=fopen("test.txt","w"); if(fp=NULL) { perror("fopen"); ...
继续访问
Java导出超大Excel文件,防止内存溢出
Java导出超大Excel文件,防止内存溢出1.采用Poi中的SXSSFWorkbook2.maven中引入Poi3.测试过程4.单元测试Java代码5.结论 将业务数据导出到Excel表中,导出任务数据量较大时,导出的项目就会内存溢出,本文通过Java操作Poi的SXSSFWorkbook类进行导出,解决内存溢出问题。 1.采用Poi中的SXSSFWorkbook 在实现excel导出时,在数据量过大的情况下,总是容易发生内存溢出的情况。可以使用POI提供的 SXSSFWorkbook 类来避免内存溢
继续访问

Apache Poi导出Excel多Sheet页详解!_奥鹏马的博客
apache poi是目前比较常用导出excel的方式。最近想要实现一个导出excel多sheet页的功能。 网上查了一下大多都是针对某个具体对象的导出,不能实现任意对象的导出。现在将自己研究出的代码贴出来,供大家参考。 //注意:此处实现的关键是将...
Apache poi 导出多sheet的excel表格_朋态圈的博客
导出多sheet的excel */public class ApachePoi { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub exportExcel();} @SuppressWarnings("resource") public static String exportExcel...
java导出excel限制大小_解决java poi导出excel2003不能超过65536行的问题
/*** 如果达到50000条数据则重新创建工作表的逻辑*/@Overridepublic void exportExcel(ListformList, ServletOutputStream outputStream){try{//工作表名后面的数字,如表1,表2int i = 0;//记录总行数int rownum = 0;//记录每个sheet的行数int tempnum = 0;//分页条...
继续访问
热门推荐 java poi 导出Excel 超大数据量解决方案
http://blog.csdn.net/qiaoshuai0920/article/details/51800991
继续访问
poi导出excel,实现一个excel中多个sheet(可解决poi导出限制65536的问题...
本文章的excel实现导出多个sheet是在上一篇poi导出的基础上实现的,这么久了,对于上一篇文章的poi也作出过一些优化。 这里我只贴修改了的方法的代码,其余的和上一篇文章的一样。 /** * 导出excel.在一个页面中单独导出Excel ...
基于Apache POI导出(百万级)大数据量Excel的实现_一朵风中摇曳的水仙...
支持单个 excel 的 sheet 导出100w 的数据 ApachePOI操作Excel对象 1.HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不经过压缩直接导出 2.XSSF:操作Excel 2007及之后版本(.xlsx)格式,内存占用高于HSSF ...
解决POI的XSSFWorkbook导入大excel的内存消耗过大问题
方式1:使用SXSSFWorkbook ,经过测试,这个情况无效,因为本质上SXSSFWorkbook 也是通过XSSFWorkbook来的,他可以解决写出excel的场景,但是解决不了我们这种用户上传且读取excel中的内容的场景 XSSFWorkbook XSSFWorkbook = new XSSFWorkbook(fileInputStream); System.gc(); SXSSFWorkbook SXSSFWorkbook = new SXSS
继续访问
导入导出
原文地址:https://blog.csdn.net/qq_29631809/article/details/72785338 创建流程:(上级为 下级的载体) 1:.创建 工作簿 2.创建 sheet(可以创建多个) 3.创建行 4.创建单元格 接下来 分别说下 工作簿的常用三种形式的区别,他们分别是 1.HSSFWorkbook 2.XSSFWorkbook 3.SXSSFWork...
继续访问
NPOI导出Excel 65536限制
1 #region NPOI 导出excel数据超65535自动分表 2 /// <summary> 3 /// DataTable转换成Excel文档流,并输出到客户端 4 /// </summary> 5 /// <param name="table">...
继续访问
java导出csv文件 为解决导出excel时每个单元格的限制(32767)
此实现方法仅供参考 因为本人导出数据量不大所采取的方法 如数据量大,会到至内存溢出请知晓 在这还提下:导出时内容自己换行 只需在内容前尾各加双引号就行。 如图 1、准备导出工具类 // An highlighted block package com.test; import java.io.BufferedWriter; import java.io.File; import java.io...
继续访问
Excel单元格数据超过32767报错问题处理
java poi 32767
继续访问
SXSSFWorkbook Excel 大量数据导出
注意 SXSSFWorkbook 用于大量数据的导出 SXSSFWorkbook是用来生成海量excel数据文件,主要原理是借助临时存储空间生成excel, SXSSFWorkbook专门处理大数据,对于大型excel的创建且不会内存溢出的,就只SXSSFWorkbook了。 它的原理很简单,用硬盘空间换内存(就像hashmap用空间换时间一样)。 SXSSFWorkbook是streami...
继续访问
EXCEL大数据量导出的解决方案
将web页面上显示的报表导出到excel文件里是一种很常见的需求。然而,当数据量较大的情况下,excel本身的支持最多65535行数据的问题便凸显出来。下面就给出大数据量导出到excel的解决方 案。 首先,对于数据超过了65535行的问题,很自然的就会想到将整个数据分块,利用excel的多sheet页的功能,将超出65535行后的数据写入到下一个sheet页中,即通过多sheet页的方式,突破了...
继续访问
几行代码,复杂Excel 导入导出,真心强大!
点击上方蓝色字体,选择“标星公众号”优质文章,第一时间送达项目中使用:功能介绍IMPORT1、 ExcelHandle核心处理器;2、 ExcelWorkbookManageexcel所有工作表管理;3、 ExcelInitConfig配置文件初始化;4、 AbstractFileParser文件转换类;alanpoi import有何优势?1、 用户不需要额外引入poi...
继续访问

java中poi导出excel问题总结
java中poi导出excel问题总结
继续访问
java POI导出excel,列数限制在256列
有两篇文章写得比较好的 https://www.oschina.net/code/snippet_1052786_47435 https://www.jianshu.com/p/4c6eec65fdc3
继续访问
apache poi导出excel最大多少个sheet
大数据导出excel大小限制
写评论

评论

收藏

点赞



分享

⑶ java中怎么把报表导出到excel

导入数据库

	@RequestMapping("/uploadOrderFile")
@ResponseBody
publicObjectuploadOrderFile(HttpServletRequestrequest,HttpServletResponseresponse,@RequestParam(value="file")MultipartFile[]files)throwsServletException,IOException,ParseException{
Workbookrwb=null;
if(files!=null&&files.length>0){
try{
//StringfilePath=request.getSession().getServletContext().getRealPath("/")+"\uploadOrderFile\"+files.getOriginalFilename();
//System.out.println("----------"+filePath);
rwb=Workbook.getWorkbook(files[0].getInputStream());
Sheetrs=rwb.getSheet(0);//默认0是第一张表,或者rwb.getSheet(Sheet1)Excel要导入的表名
intclos=rs.getColumns();//得到所有的列
introws=rs.getRows();//得到所有的行
//存放Excel表抬头名称以及对应的列
Map<Integer,Object>map=newHashMap<Integer,Object>();
//实体类集合存放每次循环获得的值
List<Medicine>medicineList=newArrayList<Medicine>();
for(inti=0;i<rows;i++){
//创建实体类
Medicinemedicine=newMedicine();
if(i==0){//遍历第一行获取抬头跟对应的列
for(intj=0;j<clos;j++){//取得每个抬头名称对应的列
if(rs.getCell(j,i).getContents().equals("品名")){
map.put(j,"品名");
}elseif(rs.getCell(j,i).getContents().equals("商品编号")){
map.put(j,"商品编号");
}elseif(rs.getCell(j,i).getContents().equals("生产日期")){
map.put(j,"生产日期");
}elseif(rs.getCell(j,i).getContents().equals("产地")){
map.put(j,"产地");
}elseif(rs.getCell(j,i).getContents().equals("生产厂家")){
map.put(j,"生产厂家");
}elseif(rs.getCell(j,i).getContents().equals("批号")){
map.put(j,"批号");
}
}
}else{
//循环遍历map》》》存的Excel表的抬头名称以及对应的列
for(intj=0;j<clos;j++){
if(map.get(j)==null){//如果=null进入下一个循环
continue;
}
if(map.get(j).equals("品名")){
//如果为空结束当前循环,进入下一个循环
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineName(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("商品编号")&&map.get(j)!=null){
//如果为空结束当前循环,进入下一个循环
if(rs.getCell(j,i).getContents()==null||rs.getCell(j,i).getContents().equals("")){
continue;
}
medicine.setMedicineCode(rs.getCell(j,i).getContents());
}elseif(map.get(j).equals("生产日期")&&map.get(j)!=null){
medicine.setCreateTime(rs.getCell(j,i).getContents());
if(rs.getCell(j,i).getContents()!=null&&!rs.getCell(j,i).getContents().equals("")){
//如果生产日期存在则+三年给到期日期赋值
//CommonUtil.getMedicineEffectiveTime为封装好的类
medicine.setEffectTime(CommonUtil.getMedicineEffectiveTime(rs.getCell(j,i).getContents(),3));
}
}elseif(map.get(j).equals("产地")&&map.get(j)!=null){
medicine.setAddress(rs.getCell(j,i).getContents());

}elseif(map.get(j).equals("生产厂家")&&map.get(j)!=null){
medicine.setProcingArea(rs.getCell(j,i).getContents());

}elseif(map.get(j).equals("批号")&&map.get(j)!=null){
medicine.setBatchNumber(rs.getCell(j,i).getContents());
}
}
medicineList.add(medicine);//获得的值放入集合中
}
}
//新增用到的list
List<Medicine>addList=newArrayList<Medicine>();
//修改用到的list
List<Medicine>updateList=newArrayList<Medicine>();
//导入数据
for(inti=0;i<medicineList.size();i++){
//判断商品编号是否存在
if(medicineService.selectMedicineCode(medicineList.get(i).getMedicineCode()).size()>0){
//如果存在则修改
updateList.add(medicineList.get(i));
}else{
addList.add(medicineList.get(i));
}
}
intupdate=0;
intadd=0;
if(updateList!=null&&updateList.size()>0){
update=medicineService.updateMedicine(updateList);
}
if(addList!=null&&addList.size()>0){
add=medicineService.addMedicine(addList);
}
if(update>0||add>0){
returnnewResponseModel().attr(ResponseModel.KEY_DATA,"数据导入成功!");
}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"数据导入失败!");
}
}catch(BiffExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}

}else{
returnnewResponseModel().attr(ResponseModel.KEY_ERROR,"没有需要导入的数据!");
}
returnnull;
}

导出

packagebeans.excel;

importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Calendar;
importjava.util.Date;

importjxl.Workbook;
importjxl.format.Colour;
importjxl.format.UnderlineStyle;
importjxl.write.Boolean;
importjxl.write.DateFormats;
importjxl.write.DateTime;
importjxl.write.Label;
importjxl.write.Number;
importjxl.write.WritableCellFormat;
importjxl.write.WritableFont;
importjxl.write.WritableSheet;
importjxl.write.WritableWorkbook;
importjxl.write.WriteException;

{
publicvoidcreateExcel(OutputStreamos)throwsWriteException,IOException{
//创建工作薄
WritableWorkbookworkbook=Workbook.createWorkbook(os);
//创建新的一页
WritableSheetsheet=workbook.createSheet("FirstSheet",0);
//构造表头
sheet.mergeCells(0,0,4,0);//添加合并单元格,第一个参数是起始列,第二个参数是起始行,第三个参数是终止列,第四个参数是终止行
WritableFontbold=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//设置字体种类和黑体显示,字体为Arial,字号大小为10,采用黑体显示
=newWritableCellFormat(bold);//生成一个单元格样式控制对象
titleFormate.setAlignment(jxl.format.Alignment.CENTRE);//单元格中的内容水平方向居中
titleFormate.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//单元格的内容垂直方向居中
Labeltitle=newLabel(0,0,"JExcelApi支持数据类型详细说明",titleFormate);
sheet.setRowView(0,600,false);//设置第一行的高度
sheet.addCell(title);

//创建要显示的具体内容
WritableFontcolor=newWritableFont(WritableFont.ARIAL);//选择字体
color.setColour(Colour.GOLD);//设置字体颜色为金黄色
WritableCellFormatcolorFormat=newWritableCellFormat(color);
Labelformate=newLabel(0,1,"数据格式",colorFormat);
sheet.addCell(formate);
Labelfloats=newLabel(1,1,"浮点型");
sheet.addCell(floats);
Labelintegers=newLabel(2,1,"整型");
sheet.addCell(integers);
Labelbooleans=newLabel(3,1,"布尔型");
sheet.addCell(booleans);
Labeldates=newLabel(4,1,"日期格式");
sheet.addCell(dates);

Labelexample=newLabel(0,2,"数据示例",colorFormat);
sheet.addCell(example);
//浮点数据
//设置下划线
WritableFontunderline=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.NO_BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(underline);
greyBackground.setBackground(Colour.GRAY_25);//设置背景颜色为灰色
Numbernumber=newNumber(1,2,3.1415926535,greyBackground);
sheet.addCell(number);
//整形数据
WritableFontboldNumber=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);//黑体
=newWritableCellFormat(boldNumber);
Numberints=newNumber(2,2,15042699,boldNumberFormate);
sheet.addCell(ints);
//布尔型数据
Booleanbools=newBoolean(3,2,true);
sheet.addCell(bools);
//日期型数据
//设置黑体和下划线
WritableFontboldDate=newWritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD,false,UnderlineStyle.SINGLE);
=newWritableCellFormat(boldDate,DateFormats.FORMAT1);
Calendarc=Calendar.getInstance();
Datedate=c.getTime();
DateTimedt=newDateTime(4,2,date,boldDateFormate);
sheet.addCell(dt);
//把创建的内容写入到输出流中,并关闭输出流
workbook.write();
workbook.close();
os.close();

}
}

⑷ java怎么实现导出excel

偶将最近写了两个导出excel的方法,第一个是面向过程的思路,就是在指定的单元格写入指定的值,如下:
/**
*负责数据导入到EXCEL
*
* @param realPath
* EXCEL表格存放的绝对路径
* @param sheetname
*
* @param xLocation
* EXCEL表格的行索引,从1开始
* @param yLocation
* EXCEL表格的列索引,从1开始
* @param value
* 需要导入的数据
*
*/
public void modifyExcel(String realPath,String sheetname,int xLocaion,int yLocation,String value){
POIFSFileSystem fs=null;
HSSFWorkbook wb=null;
try {
File file=new File(realPath);
if(file.exists()){
fs = new POIFSFileSystem(new FileInputStream(realPath));
wb=new HSSFWorkbook(fs);
HSSFSheet s=wb.getSheetAt(0);
//函数处理时横纵坐标从索引0开始
HSSFRow row=s.getRow(xLocaion-1);
HSSFCell cell=null;
if(row!=null){
cell=row.getCell(yLocation-1);
if(cell==null){
cell=row.createCell(yLocation-1);
}
}else{
row=s.createRow(xLocaion-1);
cell=row.createCell(yLocation-1);
}

cell.setCellValue(value);

}else{
wb=new HSSFWorkbook();
HSSFSheet s=wb.createSheet();
wb.setSheetName(0, sheetname);
HSSFRow row=s.createRow(xLocaion-1);
HSSFCell cell=row.createCell(yLocation-1);
cell.setCellValue(value);
}
FileOutputStream fos=new FileOutputStream(realPath);
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

第二种就是运用了对象,以对象为单位写入数据,即一个对象的所有属性在一行列出,有多少个对象就有多少行,此方法比较适用于个人信息导出之类的应用,至于导出属性的顺序问题在导出对象的实体类内部改动下即可:
/**
*负责数据导入到EXCEL
*
* @param realPath
* EXCEL表格存放的绝对路径
* @param sheetname
*
* @param users
* 需要导出到excel表的对象数组
*/
public void outputExcel(String realPath,String sheetname,UserModel[] users){
FileOutputStream fos;
try {
File file=new File(realPath);

fos = new FileOutputStream(file, true);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet s=wb.createSheet();
wb.setSheetName(0, sheetname);
HSSFRow[] rows=new HSSFRow[users.length];
HSSFCell[][] cells=new HSSFCell[20][20];
for (int i=0; i<users.length;i++) { // 相当于excel表格中的总行数
PropertyDescriptor[] descriptors=(users[i]);
rows[i]=s.createRow(i);
for (int j=0; descriptors!=null&&j<descriptors.length;j++) {
java.lang.reflect.Method readMethod = descriptors[j]
.getReadMethod();
cells[i][j]=rows[i].createCell(j);
Object value=readMethod.invoke(users[i], null);
cells[i][j].setCellValue(value.toString());

}

}
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

}

⑸ java导出excel图表

通过Java程序导出带图表的excel吗?参考下面用spire.xls.jar来创建Excel图表的方法,这里以创建饼图为例,当然你也可以指定创建其他图表类型,如柱状图、折线图、雷达图、散点图等等:

import com.spire.xls.*;

import com.spire.xls.charts.ChartSerie;

import java.awt.*;

public class CreatePieChart {

public static void main(String[] args) {

//创建Workbook对象

Workbook workbook = new Workbook();

//获取第一个工作表

Worksheet sheet = workbook.getWorksheets().get(0);

//将图表数据写入工作表

sheet.getCellRange("A1").setValue("年份");

sheet.getCellRange("A2").setValue("2002");

sheet.getCellRange("A3").setValue("2003");

sheet.getCellRange("A4").setValue("2004");

sheet.getCellRange("A5").setValue("2005");

sheet.getCellRange("B1").setValue("销售额");

sheet.getCellRange("B2").setNumberValue(4000);

sheet.getCellRange("B3").setNumberValue(6000);

sheet.getCellRange("B4").setNumberValue(7000);

sheet.getCellRange("B5").setNumberValue(8500);

//设置单元格样式

sheet.getCellRange("A1:B1").setRowHeight(15);

sheet.getCellRange("A1:B1").getCellStyle().setColor(Color.darkGray);

sheet.getCellRange("A1:B1").getCellStyle().getExcelFont().setColor(Color.white);

sheet.getCellRange("A1:B1").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);

sheet.getCellRange("A1:B1").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);

sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat(""¥"#,##0");

//添加饼图

Chart chart = sheet.getCharts().add(ExcelChartType.Pie);

//设置图表数据区域

chart.setDataRange(sheet.getCellRange("B2:B5"));

chart.setSeriesDataFromRange(false);

//设置图表位置

chart.setLeftColumn(3);

chart.setTopRow(1);

chart.setRightColumn(11);

chart.setBottomRow(20);

//设置图表标题

chart.setChartTitle("年销售额");

chart.getChartTitleArea().isBold(true);

chart.getChartTitleArea().setSize(12);

//设置系列标签

ChartSerie cs = chart.getSeries().get(0);

cs.setCategoryLabels(sheet.getCellRange("A2:A5"));

cs.setValues(sheet.getCellRange("B2:B5"));

cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);

chart.getPlotArea().getFill().setVisible(false);

//保存文档

workbook.saveToFile("output/PieChart.xlsx", ExcelVersion.Version2016);

}

}

饼图创建效果:

excel饼状图效果

⑹ 怎么用java实现导出excel

/**
*@authorliuwu
* Excel的导入与导出
*/
@SuppressWarnings({"unchecked"})
publicclassExcelOperate{
/**
*@authorliuwu
*这是一个通用的方法,利用了JAVA的反射机制,
*可以将放置在JAVA集合中并且符合一定条件的数据以EXCEL的形式输出到指定IO设备上
*@paramtitle表格标题名
*@paramheaders表格属性列名数组
*@paramdataset需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
* 此方法支持的javabean属性【数据类型有java基本数据类型及String,Date,byte[](图片转成字节码)】
*@paramout与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
*@parampattern如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*@throwsIOException
*/
publicstaticvoidexportExcel(Stringtitle,String[]headers,Collection<?>dataset,OutputStreamout,Stringpattern)throwsIOException{
//声明一个工作薄
HSSFWorkbookworkbook=newHSSFWorkbook();
//生成一个表格
HSSFSheetsheet=workbook.createSheet(title);
//设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short)20);
//生成一个样式
HSSFCellStylestyle=workbook.createCellStyle();
//设置这些样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成一个字体
HSSFFontfont=workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//把字体应用到当前的样式
style.setFont(font);
//生成并设置另一个样式
HSSFCellStylestyle2=workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//生成另一个字体
HSSFFontfont2=workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字体应用到当前的样式
style2.setFont(font2);
//产生表格标题行
HSSFRowrow=sheet.createRow(0);
for(shorti=0;i<headers.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextStringtext=newHSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍历集合数据,产生数据行
Iterator<?>it=dataset.iterator();
intindex=0;
while(it.hasNext()){
index++;
row=sheet.createRow(index);
Objectt=it.next();
//利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[]fields=t.getClass().getDeclaredFields();
for(shorti=0;i<fields.length;i++){
HSSFCellcell=row.createCell(i);
cell.setCellStyle(style2);
Fieldfield=fields[i];
StringfieldName=field.getName();
StringgetMethodName="get"
+fieldName.substring(0,1).toUpperCase()
+fieldName.substring(1);//注意实体getSet不要自己改名字不然反射会有问题
try{
ClasstCls=t.getClass();
MethodgetMethod=tCls.getMethod(getMethodName,newClass[]{});
Objectvalue=getMethod.invoke(t,newObject[]{});
HSSFRichTextStringrichString=newHSSFRichTextString(value.toString());
HSSFFontfont3=workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch(SecurityExceptione){
e.printStackTrace();
e=null;
}catch(NoSuchMethodExceptione){
e.printStackTrace();
e=null;
}catch(IllegalArgumentExceptione){
e.printStackTrace();
e=null;
}catch(IllegalAccessExceptione){
e.printStackTrace();
e=null;
}catch(InvocationTargetExceptione){
e.printStackTrace();
e=null;
}finally{
//清理资源
}
}
}
try{
workbook.write(out);
}catch(IOExceptione){
e.printStackTrace();
e=null;
}
}
}

⑺ java怎么导出excel表格

可以使用POI开源的api:
1.首先下载poi-3.6-20091214.jar,下载地址如下:
http://download.csdn.net/detail/evangel_z/3895051

2.Student.java

import java.util.Date;

public class Student
{
private int id;
private String name;
private int age;
private Date birth;

public Student()
{
}

public Student(int id, String name, int age, Date birth)
{
this.id = id;
this.name = name;
this.age = age;
this.birth = birth;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public Date getBirth()
{
return birth;
}

public void setBirth(Date birth)
{
this.birth = birth;
}

}
3.CreateSimpleExcelToDisk.java

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

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;

public class CreateSimpleExcelToDisk
{
/**
* @功能:手工构建一个简单格式的Excel
*/
private static List<Student> getStudent() throws Exception
{
List list = new ArrayList();
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

Student user1 = new Student(1, "张三", 16, df.parse("1997-03-12"));
Student user2 = new Student(2, "李四", 17, df.parse("1996-08-12"));
Student user3 = new Student(3, "王五", 26, df.parse("1985-11-12"));
list.add(user1);
list.add(user2);
list.add(user3);

return list;
}

public static void main(String[] args) throws Exception
{
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("学生表一");
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("学号");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("年龄");
cell.setCellStyle(style);
cell = row.createCell((short) 3);
cell.setCellValue("生日");
cell.setCellStyle(style);

// 第五步,写入实体数据 实际应用中这些数据从数据库得到,
List list = CreateSimpleExcelToDisk.getStudent();

for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
Student stu = (Student) list.get(i);
// 第四步,创建单元格,并设置值
row.createCell((short) 0).setCellValue((double) stu.getId());
row.createCell((short) 1).setCellValue(stu.getName());
row.createCell((short) 2).setCellValue((double) stu.getAge());
cell = row.createCell((short) 3);
cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
.getBirth()));
}
// 第六步,将文件存到指定位置
try
{
FileOutputStream fout = new FileOutputStream("E:/students.xls");
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

⑻ java导出excel

java导出Excel

java 代码 /* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.axon.fable.sams.view.action; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.serv ...

java导出Excel例举方式
方法一:导出Excel数据的插件jexcelapi

程序实例如下:
public void exportClassroom(OutputStream os) throws PaikeException {

try {
WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件
WritableSheet wsheet = wbook.createSheet("教室信息表", 0); //工作表名称
//设置Excel字体
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat titleFormat = new WritableCellFormat(wfont);
String[] title = { "教室名", "容 量", "类 型", "其他说明" };
//设置Excel表头
for (int i = 0; i < title.length; i++) {
Label excelTitle = new Label(i, 0, title[i], titleFormat);
wsheet.addCell(excelTitle);
}
int c = 1; //用于循环时Excel的行号
ClassroomService cs = new ClassroomService();
List list = cs.findAllClassroom(); //这个是从数据库中取得要导出的数据
Iterator it = list.iterator();
while (it.hasNext()) {
ClassroomDTO crdto = (ClassroomDTO) it.next();
Label content1 = new Label(0, c, crdto.getRoomname());
Label content2 = new Label(1, c, crdto.getCapicity().toString());
Label content3 = new Label(2, c, crdto.getRoomTypeId()
.toString());
Label content4 = new Label(3, c, crdto.getRemark());
wsheet.addCell(content1);
wsheet.addCell(content2);
wsheet.addCell(content3);
wsheet.addCell(content4);
c++;
}

wbook.write(); //写入文件
wbook.close();
os.close();
} catch (Exception e) {

throw new PaikeException("导出文件出错");

}

}

方法二:直接用Java代码实现导出Excel报表

/*

* Generated by MyEclipse Struts

* Template path: templates/java/JavaClass.vtl

*/

package com.axon.fable.sams.view.action;

import java.io.IOException;

import java.io.OutputStream;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.axon.fable.empolderpackage.out.OutJavaScript;

import com.axon.fable.empolderpackage.page.Pager;

import com.axon.fable.empolderpackage.string.MyPublic;

import com.axon.fable.sams.common.BaseAction;

import com.axon.fable.sams.exception.AppBusinessException;

import com.axon.fable.sams.exception.AppSystemException;

/**

* MyEclipse Struts

* Creation date: 06-28-2007

*

* XDoclet definition:

* @struts.action path="/axon" name="axonForm" input="/samspage/zm/axon.jsp" parameter="method" scope="request" validate="true"

* @struts.action-forward name="success" path="/samspage/zm/content.jsp"

*/

public class StshipoperationAction extends BaseAction {

/*

* Generated Methods

*/

private static Session session=null;

private static Transaction ts=null;

private static Query queryC=null;

private static Query queryR=null;

private static Query query=null;

private static List list=null;

private static Integer startRow;

private static Integer ncurrentPage;

private static Integer cell;

private static String property;

private static String sql;

private static String type;

private static String condition ;//是否导出当前页

private static String currentPage;

private static String from ;

private static String pactdata;

private static String voyagename;

private static String voyageno;

private static String dwt ;

private static String hirefrom ;

private static String deliveryposion ;

private static String redeliveryposion ;

private static String sheepowner ;

private static String addr;

private static String addcomm;

private static String rent;

private static String fileName ;

private static OutputStream os;

@Override

public ActionForward findAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward findById(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

@Override

public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

public static String strNull(Object nullStr,String newStr,Integer cell){

if(nullStr==null||nullStr.equals("")){return newStr;}else{cell+=1;return nullStr+"";}

}

public static String getStr(String str,Integer cell){

if(str==null||str.trim().equals("")){return "";}else{cell+=1;return ","+str;}

}

public static String getExcelTile(String title){

if(title==null)

return "";

if(title.equals("modela.stsid"))

return "编号";

if(title.equals("modelc.pactdata"))

return "合同日期";

if(title.equals("modela.voyagename"))

return "航名";

if(title.equals("modela.voyageno"))

return "航次";

if(title.equals("modelc.dwt"))

return "DWT";

if(title.equals("modelc.hirefrom"))

return "受载期";

if(title.equals("modela.deliveryposion"))

return "交船地点";

if(title.equals("modela.redeliveryposion"))

return "还船地点";

if(title.equals("modelc.sheepowner"))

return "联系人";

if(title.equals("modelc.addr"))

return "经纪人拥金";

if(title.equals("modelc.addcomm"))

return "ADD COMM";

if(title.equals("modelc.rent"))

return "租金";

return "";

}

public ActionForward exporVoyagesInfoToExcel(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

list=null;

startRow=0;

ncurrentPage=1;

cell=0;

type =request.getParameter("type");

condition =request.getParameter("condition");//是否导出当前页

currentPage =request.getParameter("currentPage");

from =request.getParameter("from");

pactdata = request.getParameter("modelc.pactdata");

voyagename = request.getParameter("modela.voyagename");

voyageno = request.getParameter("modela.voyageno");

dwt = request.getParameter("modelc.dwt");

hirefrom = request.getParameter("modelc.hirefrom");

deliveryposion = request.getParameter("modela.deliveryposion");

redeliveryposion = request.getParameter("modela.redeliveryposion");

sheepowner = request.getParameter("modelc.sheepowner");

addr = request.getParameter("modelc.addr");

addcomm = request.getParameter("modelc.addcomm");

rent = request.getParameter("modelc.rent");

if(type!=null&&type.trim().equals("1")){

type ="已还船舶--费用未结清";

}else{

type ="已还船舶--费用已结清";

}

property =getStr(pactdata,cell)+getStr(voyagename,cell)+getStr(voyageno,cell)+getStr(dwt,cell)+getStr(hirefrom,cell)

+getStr(deliveryposion,cell)+getStr(redeliveryposion,cell)+getStr(sheepowner,cell)+getStr(addr,cell)+getStr(addcomm,cell)

+getStr(rent,cell);

property = property.substring(1);

String split[] = property.split(",");

// System.out.println("-----------------------------property:"+property);

if(currentPage!=null&&!currentPage.trim().equals("")){

ncurrentPage =Integer.parseInt(currentPage);

}else{

OutJavaScript.outString(response, "Sorry! Failed to get information of pager.");

return null;

}

try {

session =getServiceLocator().getBaseHibernateDAO().getSession();

sql ="select count(*) "+from;

query =session.createQuery(sql);

list = query.list();

for (int i = 0; i < list.size(); i++) {

totalSize =(Integer)list.get(i);

if(totalSize!=0){

pager =new Pager(ncurrentPage,totalSize);

}

}

query =getServiceLocator().getBaseHibernateDAO().getSession().createQuery("select " +property+from);

if(condition!=null&&condition.trim().equals("1")){//分页数据

startRow = (ncurrentPage - 1)*pager.getPageSize();

query.setFirstResult(startRow);

query.setMaxResults(pager.getPageSize());

// System.out.println("---------------------------------------------------query:"+query);

}

list = query.list();

fileName = "shipInfo";

os = response.getOutputStream();

response.reset();

response.setHeader("Content-disposition",

"attachment; filename=" +fileName + ".xls");

response.setContentType("application/msexcel");

jxl.write.WritableWorkbook wbook = Workbook.createWorkbook(os);

jxl.write.WritableSheet wsheet = wbook.createSheet("the first sheet", 0);

for (int i = 0; i < split.length; i++) {

jxl.write.Label wlabel0;

wlabel0 = new jxl.write.Label(i, 0, getExcelTile(split[i]));

wsheet.addCell(wlabel0);

}

jxl.write.Label wlabel1;

for(int i=0;i<list.size();i++) {

if(split.length==1){

Object strval = (Object) list.get(i);

String javaScript=""+MyPublic.toHtmlStr(strval==null?"":strval.toString().trim())+"";

wlabel1 = new jxl.write.Label(0, i+1,strval==null?"":strval.toString().trim() );

wsheet.addCell(wlabel1);

}else{

Object[] strval = (Object[]) list.get(i);

for(int j=0;j<strval.length;j++) {

String javaScript=""+MyPublic.toHtmlStr(strval[j]==null?"":strval[j].toString().trim())+"";

//System.out.println("===================script:"+javaScript);

wlabel1 = new jxl.write.Label(j, i+1,strval[j]==null?"":strval[j].toString().trim() );

wsheet.addCell(wlabel1);

}

}

}

wbook.write();

response.flushBuffer();

wbook.close();

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (HibernateException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (AppSystemException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! System exception.");

e1.printStackTrace();

} catch (AppBusinessException e1) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Database exception.");

e1.printStackTrace();

} catch (RowsExceededException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

} catch (WriteException e) {

// TODO Auto-generated catch block

OutJavaScript.outString(response, "Sorry! Export Excel exception.");

e.printStackTrace();

}

return null;

}

@Override

public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

// TODO Auto-generated method stub

return null;

}

}

还有其他很多种 字数限制 无法一一举例方式

阅读全文

与java导出excel报表相关的资料

热点内容
台湾经典动作片有哪些 浏览:578
团鬼六所有电影下载 浏览:664
动车如何退票app 浏览:59
javacalendar时分秒 浏览:300
邱淑贞拍过的r 浏览:384
日本胸大电影 浏览:366
武打片经典老电影1001武打片经典老电影 浏览:158
2t便携式硬盘文件夹取名字 浏览:849
儿童篮球电影 浏览:957
使用命令查字符查看ipv4地址 浏览:937
英文绘本在app哪里看 浏览:671
老电影水生 浏览:727
python查询数据库结果保存 浏览:53
阿鲁小表情文件夹 浏览:69
《龙猫》的导演是? 浏览:520
大尺度电影百度网盘链接 浏览:280
大话西游2粤语1080下载 浏览:312
课程app哪里找 浏览:515
pe模式下能格式化加密狗吗 浏览:794
pdfpmf 浏览:671