struts2导出excel无法找到InputStream
错误:java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [] in the invocation stack. Check the <param name="inputName"> tag specified for this action说是我栈中没有excelStream。
环境:struts2.3.15+spring3+hibernate4
其他环境有:druid+javamelody
使用的是jxl导出excel
从数据库查询数据,不是读取的文件。
action:
public String filename;
public InputStream excelStream;
get、set方法省略....
public String exportExcel() {
ByteArrayOutputStream targetFile = new ByteArrayOutputStream();
try {
WritableWorkbook workbook = Workbook.createWorkbook(targetFile);
WritableSheet sheet = workbook.createSheet("测试报告", 0);
......其他省略
workbook.write();
workbook.close();
} catch (Exception e) {
System.out.println("在输出到EXCEL的过程中出现错误,错误原因:" + e.toString());
}
excelStream = new ByteArrayInputStream(targetFile.toByteArray());
System.out.println("===================================="+excelStream);
}
struts配置文件:
<result name="excel" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">excelStream</param>
<param name="contentDisposition">attachment;filename="test.xls"</param>
<param name="bufferSize">1024</param>
</result>
打印出来的inputStream:
====================================java.io.ByteArrayInputStream@124a60b
不是空的啊。
在struts2.18中也是使用的同样的方法,可以导出,但这是什么个情况?,请教大神,很急!!!
--------------------编程问答-------------------- 在线坐等答案 --------------------编程问答-------------------- 你这个action方法中没有return?! --------------------编程问答--------------------
有,当然有,没贴出来,写法肯定是没错,估计是配置的问题。
第一次使用druid+javamelody,不知道是不是跟他们相关,各位大神支个招! --------------------编程问答-------------------- 如果没有读到这个excel,也就是没有流也会出现这个这个错误的。 --------------------编程问答-------------------- 至少有一个方法是
public InputStream getExcelStream()
才对的。 --------------------编程问答--------------------
不是赌气excel文件,是我直接用WritableWorkbook 创建的,数据是从数据库查询出来的,查询出来后用WritableWorkbook 创建的,完整 的代码:
--------------------编程问答--------------------
public String exportExcel() {
ByteArrayOutputStream targetFile = new ByteArrayOutputStream();
try {
/** **********创建工作簿************ */
WritableWorkbook workbook = Workbook.createWorkbook(targetFile);
/** **********创建工作表************ */
WritableSheet sheet = workbook.createSheet("测试报告", 0);// 定义sheet名,第几个sheet
/** *********设置列宽**************** */
sheet.setColumnView(0, 20); // 第1列
sheet.setColumnView(1, 18); // 第2列
sheet.setColumnView(2, 30);// 第3列
sheet.setColumnView(3, 30);// 第4列
sheet.setColumnView(4, 15);// 第5列
sheet.setColumnView(5, 30);// 第6列
sheet.setColumnView(6, 15);// 第7列
sheet.setColumnView(7, 30);// 第7列
sheet.setColumnView(8, 25);// 第7列
// 设置行高
sheet.setRowView(0, 600, false);
sheet.setRowView(1, 400, false);
// 设置页边距
sheet.getSettings().setRightMargin(0.5);
// 设置页脚
// sheet.setFooter("", "", "测试页脚");
/** ************设置单元格字体************** */
// 字体
WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 14,
WritableFont.BOLD);
/** ************以下设置几种格式的单元格************ */
// 用于标题
WritableCellFormat wcf_title = new WritableCellFormat(BoldFont);
wcf_title.setAlignment(Alignment.CENTRE);
wcf_title.setWrap(true); // 是否换行
// 用于正文左
WritableCellFormat wcf_center = new WritableCellFormat(NormalFont);
wcf_center.setAlignment(Alignment.LEFT);
WritableCellFormat wcf_table = new WritableCellFormat(NormalFont);
wcf_table.setAlignment(Alignment.CENTRE);
/** ************单元格格式设置完成****************** */
// 合并单元格,注意mergeCells(col0,row0,col1,row1)
// --列从0开始,col1为你要合并到第几列,行也一样
sheet.mergeCells(0, 0, 26, 0);
//sheet.addCell(new Label(0, 0, "测试报告", wcf_title));
// 另起一table
sheet.addCell(new Label(0, 1, "测试编号", wcf_table));
sheet.addCell(new Label(1, 1, "厂商名称", wcf_table));
sheet.addCell(new Label(2, 1, "车牌号", wcf_table));
sheet.addCell(new Label(3, 1, "车长", wcf_table));
sheet.addCell(new Label(4, 1, "检测时间", wcf_table));
sheet.addCell(new Label(5, 1, "厂商检测时间", wcf_table));
sheet.addCell(new Label(6, 1, "车速", wcf_table));
sheet.addCell(new Label(7, 1, "厂商车速", wcf_table));
sheet.addCell(new Label(8, 1, "车速差", wcf_table));
HqlFilter hqlFilter = new HqlFilter(getRequest());
List<StatData> list = service.findByFilter(hqlFilter);
for (int i = 0; i < list.size(); i++) { //
StatData data = (StatData) list.get(i);
sheet.addCell(new Label(0, 2 + i, data.getWorksNo(), wcf_center));
sheet.addCell(new Label(1, 2 + i, data.getWorksName(), wcf_center));
sheet.addCell(new Label(2, 2 + i, data.getCarNoR(), wcf_center));
sheet.addCell(new Label(3, 2 + i, data.getCarLengthR().toString(), wcf_center));
if (data.getWatchTimeR() != null) {
String dateTime = String.valueOf(data.getWatchTimeR());
sheet.addCell(new Label(4, 2 + i,dateTime.split("\\.")[0], wcf_center));
}else{
sheet.addCell(new Label(4, 2 + i,"", wcf_center));
}
if (data.getWatchTimeC() != null) {
String dateTime = String.valueOf(data.getWatchTimeC());
sheet.addCell(new Label(5, 2 + i,dateTime.split("\\.")[0], wcf_center));
}else{
sheet.addCell(new Label(5, 2 + i,"", wcf_center));
}
sheet.addCell(new Label(6, 2 + i, data.getCarSpeedAverageR().toString(), wcf_center));
sheet.addCell(new Label(7, 2 + i, data.getCarSpeedC().toString(),wcf_center));
Double per = data.getSpeedDiffer()/data.getCarSpeedAverageR();
sheet.addCell(new Label(8, 2 + i, data.getSpeedDiffer().toString()+","+per+"%",wcf_center));
}
/** **********以上所写的内容都是写在缓存中的,下一句将缓存的内容写到文件中******** */
workbook.write();
/** *********关闭文件************* */
workbook.close();
// 导出名称
//filename = new String("测试报告.xls".getBytes(), "ISO8859-1");
} catch (Exception e) {
System.out.println("在输出到EXCEL的过程中出现错误,错误原因:" + e.toString());
}
excelStream = new ByteArrayInputStream(targetFile.toByteArray());
System.out.println("===================================="+excelStream);
// try {
// excelStream.close();
// } catch (IOException e) {
// System.out.println("关闭inputStream异常:" + e.toString());
// e.printStackTrace();
// } finally {
// if (excelStream != null) {
// try {
// excelStream.close();
// } catch (IOException e) {
// System.out.println("关闭inputStream异常:" + e.toString());
// e.printStackTrace();
// }
// }
// }
return "excel";
public String filename;
public InputStream excelStream;
都有完整的get和set方法
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public InputStream getExcelStream() {
return excelStream;
}
public void setExcelStream(InputStream excelStream) {
this.excelStream = excelStream;
}
--------------------编程问答-------------------- 既然用struts了,就要遵从人家的规则,你把流传给excelStream试试,有set、get方法有啥用,又没值。 --------------------编程问答--------------------
传出去了啊,
excelStream = new ByteArrayInputStream(targetFile.toByteArray());
System.out.println("===================================="+excelStream);
而且打印excelStream 也不为空,在使用struts2.18的时候都是这么写的,升级成2.3.15就找不行了。写法还是没错的 --------------------编程问答-------------------- excelStream = new ByteArrayInputStream(targetFile.toByteArray());
System.out.println("===================================="+excelStream);
你在这里打印,没值才怪,在要调用的方法内打印才对。 --------------------编程问答--------------------
我就算这么写也一样(最下面的get代码):
--------------------编程问答--------------------
public String filename;
public InputStream excelStream;
ByteArrayOutputStream targetFile = null;
public String exportExcel() {
targetFile = new ByteArrayOutputStream();
try {
/** **********创建工作簿************ */
WritableWorkbook workbook = Workbook.createWorkbook(targetFile);
/** **********创建工作表************ */
WritableSheet sheet = workbook.createSheet("测试报告", 0);// 定义sheet名,第几个sheet
/** *********设置列宽**************** */
sheet.setColumnView(0, 20); // 第1列
sheet.setColumnView(1, 18); // 第2列
sheet.setColumnView(2, 30);// 第3列
sheet.setColumnView(3, 30);// 第4列
sheet.setColumnView(4, 15);// 第5列
sheet.setColumnView(5, 30);// 第6列
sheet.setColumnView(6, 15);// 第7列
sheet.setColumnView(7, 30);// 第7列
sheet.setColumnView(8, 25);// 第7列
// 设置行高
sheet.setRowView(0, 600, false);
sheet.setRowView(1, 400, false);
// 设置页边距
sheet.getSettings().setRightMargin(0.5);
// 设置页脚
// sheet.setFooter("", "", "测试页脚");
/** ************设置单元格字体************** */
// 字体
WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 14,
WritableFont.BOLD);
/** ************以下设置几种格式的单元格************ */
// 用于标题
WritableCellFormat wcf_title = new WritableCellFormat(BoldFont);
wcf_title.setAlignment(Alignment.CENTRE);
wcf_title.setWrap(true); // 是否换行
// 用于正文左
WritableCellFormat wcf_center = new WritableCellFormat(NormalFont);
wcf_center.setAlignment(Alignment.LEFT);
WritableCellFormat wcf_table = new WritableCellFormat(NormalFont);
wcf_table.setAlignment(Alignment.CENTRE);
/** ************单元格格式设置完成****************** */
// 合并单元格,注意mergeCells(col0,row0,col1,row1)
// --列从0开始,col1为你要合并到第几列,行也一样
sheet.mergeCells(0, 0, 26, 0);
//sheet.addCell(new Label(0, 0, "测试报告", wcf_title));
// 另起一table
sheet.addCell(new Label(0, 1, "测试编号", wcf_table));
sheet.addCell(new Label(1, 1, "厂商名称", wcf_table));
sheet.addCell(new Label(2, 1, "车牌号", wcf_table));
sheet.addCell(new Label(3, 1, "车长", wcf_table));
sheet.addCell(new Label(4, 1, "检测时间", wcf_table));
sheet.addCell(new Label(5, 1, "厂商检测时间", wcf_table));
sheet.addCell(new Label(6, 1, "车速", wcf_table));
sheet.addCell(new Label(7, 1, "厂商车速", wcf_table));
sheet.addCell(new Label(8, 1, "车速差", wcf_table));
HqlFilter hqlFilter = new HqlFilter(getRequest());
List<StatData> list = service.findByFilter(hqlFilter);
for (int i = 0; i < list.size(); i++) { //
StatData data = (StatData) list.get(i);
sheet.addCell(new Label(0, 2 + i, data.getWorksNo(), wcf_center));
sheet.addCell(new Label(1, 2 + i, data.getWorksName(), wcf_center));
sheet.addCell(new Label(2, 2 + i, data.getCarNoR(), wcf_center));
sheet.addCell(new Label(3, 2 + i, data.getCarLengthR().toString(), wcf_center));
if (data.getWatchTimeR() != null) {
String dateTime = String.valueOf(data.getWatchTimeR());
sheet.addCell(new Label(4, 2 + i,dateTime.split("\\.")[0], wcf_center));
}else{
sheet.addCell(new Label(4, 2 + i,"", wcf_center));
}
if (data.getWatchTimeC() != null) {
String dateTime = String.valueOf(data.getWatchTimeC());
sheet.addCell(new Label(5, 2 + i,dateTime.split("\\.")[0], wcf_center));
}else{
sheet.addCell(new Label(5, 2 + i,"", wcf_center));
}
sheet.addCell(new Label(6, 2 + i, data.getCarSpeedAverageR().toString(), wcf_center));
sheet.addCell(new Label(7, 2 + i, data.getCarSpeedC().toString(),wcf_center));
Double per = data.getSpeedDiffer()/data.getCarSpeedAverageR();
sheet.addCell(new Label(8, 2 + i, data.getSpeedDiffer().toString()+","+per+"%",wcf_center));
}
/** **********以上所写的内容都是写在缓存中的,下一句将缓存的内容写到文件中******** */
workbook.write();
/** *********关闭文件************* */
workbook.close();
// 导出名称
//filename = new String("测试报告.xls".getBytes(), "ISO8859-1");
} catch (Exception e) {
System.out.println("在输出到EXCEL的过程中出现错误,错误原因:" + e.toString());
}
return "excel";
}
public InputStream getExcelStream() {
excelStream = new ByteArrayInputStream(targetFile.toByteArray());
return excelStream;
}
public void setExcelStream(InputStream excelStream) {
this.excelStream = excelStream;
}
<!-- 导出excel -->
<action name="daochuexcel" class="com.wuliuguanli.action.DaochuExcelAction">
<result name="excel" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition"> attachment;filename="${fileName}.xls"</param>
<param name="inputName">excelStream</param>
</result>
</action>
package com.wuliuguanli.action;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import com.wuliuguanli.WuliuguanliAction;
import com.wuliuguanli.dao.WuliuguanliDao;
import com.wuliuguanli.entity.Business;
import com.wuliuguanli.util.WuliuguanliException;
@Controller
public class DaochuExcelAction extends WuliuguanliAction{
@Resource WuliuguanliDao dao;
//input
private String ids;
private String fileName;//文件名
//output
private String tempPath;//临时文件目录
public String execute(){
initExcel();
return "excel";
}
public void initExcel(){
String[] ids1=ids.split("-");
// System.out.println(ids1.length);
// for(int i=0;i<ids1.length;i++){
// System.out.println(ids1[i]);
// }
List<Business> bs=new ArrayList<Business>();
int i=0;
for(i=0;i<ids1.length;i++){
Business b=new Business();
try {
b=dao.findBusinessById(Integer.parseInt(ids1[i]));
if(null!=b){
b.setState(1);
dao.insertBusiness(b);
bs.add(b);
}
//模版的绝对路径
String path="/Edu/exceltemplet/";
String filepath=ServletActionContext.getServletContext().getRealPath(path+fileName+".xls");
FileInputStream fis=new FileInputStream(filepath);
ExcelUtils eu=new ExcelUtils();
tempPath=eu.exportExcel(fis, "temp/"+createFileName(), fileName, bs);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WuliuguanliException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public InputStream getExcelStream() {
return ServletActionContext.getServletContext().getResourceAsStream("/Edu/exceltemplet/"+tempPath);
}
/**
* 以年月日时分秒毫秒+4位随机数的格式来创建一个文件名,不带扩展名
* @return 文件名
*/
public static String createFileName() {
StringBuffer sb = new StringBuffer();
Date date = new Date();
//获取年月日时分秒
sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(date));
//毫秒
String milli = String.valueOf(date.getTime() % 1000);
while (milli.length() < 3) {
milli = "0" + milli;
}
sb.append(milli);
//四位随机数
String rondom = String.valueOf(new Random().nextInt(10000));
while (rondom.length() < 4) {
rondom = "0" + rondom;
}
sb.append(rondom);
return sb.toString();
}
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getTempPath() {
return tempPath;
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
}
package com.wuliuguanli.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.struts2.ServletActionContext;
import com.wuliuguanli.entity.Business;
/**
* 操作excel工具类
* @author think
*
*/
public class ExcelUtils {
/**
* @param sheet 要添加数据的工作表
* @param list 填充的数据
*/
public void addCellOfBug(WritableSheet sheet, List<Business> bs,int count,int page) {
if(count<=20){
try {
for(int i=0;i<bs.size();i++){
sheet.addCell(new Label(0,8+i,i+1+""));
sheet.addCell(new Label(1,8+i,bs.get(i).getProductName()));
sheet.addCell(new Label(2,8+i,bs.get(i).getSonghuoren()));
sheet.addCell(new Label(3,8+i,bs.get(i).getPeopleByReceiverPeopleId().getName()));
sheet.addCell(new Label(4,8+i,bs.get(i).getPeopleByReceiverPeopleId().getPhone()));
sheet.addCell(new Label(5,8+i,bs.get(i).getPeopleByReceiverPeopleId().getAddress()));
sheet.addCell(new Label(7,8+i,bs.get(i).getNumber()+""));
sheet.addCell(new Label(8,8+i,bs.get(i).getBeizhu()));
}
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
for(int i=20;i<bs.size();i++){
sheet.addCell(new Label(0,8+i-20,i+1+""));
sheet.addCell(new Label(1,8+i-20,bs.get(i).getProductName()));
sheet.addCell(new Label(2,8+i-20,bs.get(i).getSonghuoren()));
sheet.addCell(new Label(3,8+i-20,bs.get(i).getPeopleByReceiverPeopleId().getName()));
sheet.addCell(new Label(4,8+i-20,bs.get(i).getPeopleByReceiverPeopleId().getPhone()));
sheet.addCell(new Label(5,8+i-20,bs.get(i).getPeopleByReceiverPeopleId().getAddress()));
sheet.addCell(new Label(7,8+i-20,bs.get(i).getNumber()+""));
sheet.addCell(new Label(8,8+i-20,bs.get(i).getBeizhu()));
}
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 得到实际保存文件根目录
*/
public static String getRootPath() {
return ServletActionContext.getServletContext().getRealPath("").replace("\\", "/") + "/Edu/exceltemplet/";
}
/**
* 输出excel
* @param is 原始excel模版输入流
* @param path 临时文件目录
* @param fileName 文件名
* @param list 要填充的数据
* @return 返回相对临时文件的目录
*/
public String exportExcel(InputStream is, String path, String fileName, List<Business> fahuo) {
//临时目录,用于生成临时文件
String tempPath = null ;
WritableWorkbook wb = null;
File f = new File(getRootPath() + path);
//不存在则创建它
if (!f.exists())
f.mkdirs();
tempPath = getRootPath() + path + "/" + fileName + ".xls";
final File file = new File(tempPath);
OutputStream oss = null;
try {
//创建临时文件
if(file.createNewFile()){
oss = new FileOutputStream(file);
wb = Workbook.createWorkbook(oss, Workbook.getWorkbook(is));
int count=fahuo.size();//得到fahuo物品中的组件个数
if(count<=20){//分页 曹传奎
WritableSheet sheet = wb.getSheet(0);
if ("sample".equals(fileName)) {
addCellOfBug(sheet, fahuo,count,count/20);
}
wb.write();
}else{
WritableSheet[] sheet = wb.getSheets();
if ("sample".equals(fileName)) {
addCellOfBug(sheet[0], fahuo,count,count/20-1);
addCellOfBug(sheet[1], fahuo,count,count/20);
}
wb.write();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
wb.close();
oss.flush();
oss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/***
*
* Thread.sleep(20000) 只是测试用的,当然实际情况可以设置为1小时,差不多了
* 还有在tomcat启动时,就删除Edu/exceltemplet/temp下所有文件,避免临时文件夹及文件某些特殊原因没有删除而导致太多
* **/
//过一段时间之后,删除临时文件
new Thread(new Runnable() {
public void run() {
try {
// 线程睡20秒
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 删除临时文件
file.delete();
}
}).start();
return path + "/" + fileName + ".xls";
}
}
以上是我写的导出excel的代码,你参考一下吧,应该差不多吧 --------------------编程问答-------------------- 我都这么写了,还是不行,我去年易做图!
--------------------编程问答-------------------- 谁能告诉我struts2那些易做图件对InputStream有影响。我检测了几遍配置文件也没发现那有问题。 --------------------编程问答-------------------- 未解决,关闭吧
public InputStream getExcelStream() throws FileNotFoundException {
File file = new File("D:/nongyelanmu.xls");
return new FileInputStream(file);
//return excelStream;
}
补充:Java , Web 开发