sturts2和jxl生成excel文件(输出流)

struts.xml

<action name="action_*" method="{1}" class="Action">
<result name="toDownloadExcle" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>

如果输出名字fileName中存在汉字,需要转码
public String getFileName() {
try { 
fileName= new String(fileName.getBytes(), "ISO8859-1"); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } 
return fileName;
}




action


public String mainSearchExport() throws Exception {
// 系统生成文件的名称
fileName = "fileName"
+ new SimpleDateFormat("yyyy-MM-dd").format(new Date(System
.currentTimeMillis())) + ".xls";
executeExport(fileName, titles);
return "toDownloadExcle";
}
/**
* 执行excel导出
*
* @param fileName
* @param titles
* @throws Exception
*/
public void executeExport(String fileName, String[] titles)
throws Exception {
inputStream = eo.writeToExcle(titles, data);
// 下载文件的名称
this.fileName = new String(fileName.getBytes(), "ISO-8859-1");
}






import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;

public class ExcelOperate {
/**
* 将数据写入excle文件
* @param titles 第一行标题
* @param data 数据列表
* @throws IOException
* @throws RowsExceededException
* @throws WriteException
*/
public  InputStream writeToExcle(String[] titles, List data) throws IOException, RowsExceededException, WriteException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
WritableWorkbook book = Workbook.createWorkbook(os);
WritableSheet sheet = book.createSheet("Sheet1", 0);
int titleLength = titles.length;
if (titles != null && titleLength > 0) {
for (int i=0; i < titleLength; i++) {
String title = titles[i];
Label label = new Label(i, 0, title);
sheet.addCell(label);
sheet.setColumnView(i, 20);
}
}

if (data != null && data.size() > 0 ) {
int rowsNum = 1;
int colsNum = 0;
for (int j=0; j<data.size(); j++) {
String obj = data.get(j) + "";
if (j > 0 && j%titleLength==0) {
rowsNum++;
colsNum = 0;
}
Label label = new Label(colsNum++, rowsNum, obj);
sheet.addCell(label);
}
}

book.write();
book.close();
return new ByteArrayInputStream(os.toByteArray());
}
}

你可能感兴趣的:(java,struts,Excel,OS,J#)