首先我们需要一个方法
<action name="ExporGXtXlsFile" class="UschoolAction" method="ExporGXtXlsFile">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="inputName">targetFileInputStream</param>
<param name="bufferSize">1024</param>
</result>
</action>
比如我是这样配置的,方法名是ExporGXtXlsFile
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public String ExportXlsFile()throws Exception{
首先我们可以获取一些参数,比如姓名啊,学校啊 什么的
然后根据条件和方法查出来数据
比如导出的是list<user> list=new ArrayList<user>();用来存数据
然后我们定义一个List<Map<String,Object>>集合来定义excel的头部信息
List<Map<String, Object>> headInfoList = new ArrayList<Map<String,Object>>();
头部就是类比下边这样定义的
Map<String, Object> itemMap = new HashMap<String, Object>();
itemMap.put("title", "排序"); //这个是头部名称
itemMap.put("columnWidth", 25); //这个是宽度
itemMap.put("dataKey", "XH1") ;//这个是别名
headInfoList.add(itemMap); //这个是存到之前定义的集合中
itemMap = new HashMap<String, Object>();
itemMap.put("title", "学校");
itemMap.put("columnWidth", 50);
itemMap.put("dataKey", "XH2");
headInfoList.add(itemMap);
然后定义一个List<Map<String,Object>>集合用来存数据
List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
Map<String, Object> dataItem = null;
int i =1;
//遍历我们之前得到的list,然后存入数据,存到之前对应的xh1,xh2
for (user dto : list) {
dataItem = new HashMap<String, Object>();
dataItem.put("XH1", i++);
dataItem.put("XH2", dto.getU_schoole());
dataList.add(dataItem);//添加到集合里边
}
String path = ConstantDefinition.SAVEPATH;
try {
POIUtil poiUtil = new POIUtil();
//1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiUtil.getHSSFWorkbook();
//2.创建 Sheet
HSSFSheet hssfSheet = poiUtil.getHSSFSheet(hssfWorkbook, "sheet");
//3.写入 head
poiUtil.writeHeader(hssfWorkbook, hssfSheet, headInfoList);
//4.写入内容
poiUtil.writeContent(hssfWorkbook, hssfSheet, 1, headInfoList, dataList);
//5.保存文件到filePath中
poiUtil.write2FilePath(hssfWorkbook, path+dateString+".xls");
fileName=dateString+".xls";
filePath =new FileInputStream( path+"/"+fileName);
} catch (Exception e) {
e.printStackTrace();
}
//response.getWriter().print(listinfo);
return this.SUCCESS ;
}
public InputStream getTargetFileInputStream() throws FileNotFoundException{
System.out.println("---------------------------------->"+fileName);
return filePath;
}
//上边方法写的很清楚了,剩下的我就把工具类给拼上就完了
package com.bistone.utils;
import org.apache.poi.hssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* poi 导出excel 工具类
*/
public class POIUtil {
/**
* 1.创建 workbook
* @return
*/
public HSSFWorkbook getHSSFWorkbook(){
return new HSSFWorkbook();
}
/**
* 2.创建 sheet
* @param hssfWorkbook
* @param sheetName sheet 名称
* @return
*/
public HSSFSheet getHSSFSheet(HSSFWorkbook hssfWorkbook, String sheetName){
return hssfWorkbook.createSheet(sheetName);
}
/**
* 3.写入表头信息
* @param hssfWorkbook
* @param hssfSheet
* @param headInfoList List<Map<String, Object>>
* key: title 列标题
* columnWidth 列宽
* dataKey 列对应的 dataList item key
*/
public void writeHeader(HSSFWorkbook hssfWorkbook,HSSFSheet hssfSheet ,List<Map<String, Object>> headInfoList){
HSSFCellStyle cs = hssfWorkbook.createCellStyle();
HSSFFont font = hssfWorkbook.createFont();
font.setFontHeightInPoints((short)12);
font.setBoldweight(font.BOLDWEIGHT_BOLD);
cs.setFont(font);
cs.setAlignment(cs.ALIGN_CENTER);
HSSFRow r = hssfSheet.createRow(0);
r.setHeight((short) 380);
HSSFCell c = null;
Map<String, Object> headInfo = null;
//处理excel表头
for(int i=0, len = headInfoList.size(); i < len; i++){
headInfo = headInfoList.get(i);
c = r.createCell(i);
c.setCellValue(headInfo.get("title").toString());
c.setCellStyle(cs);
if(headInfo.containsKey("columnWidth")){
hssfSheet.setColumnWidth(i, (short)(((Integer)headInfo.get("columnWidth") * 8) / ((double) 1 / 20)));
}
}
}
/**
* 4.写入内容部分
* @param hssfWorkbook
* @param hssfSheet
* @param startIndex 从1开始,多次调用需要加上前一次的dataList.size()
* @param headInfoList List<Map<String, Object>>
* key: title 列标题
* columnWidth 列宽
* dataKey 列对应的 dataList item key
* @param dataList
*/
public void writeContent(HSSFWorkbook hssfWorkbook,HSSFSheet hssfSheet ,int startIndex,
List<Map<String, Object>> headInfoList, List<Map<String, Object>> dataList){
Map<String, Object> headInfo = null;
HSSFRow r = null;
HSSFCell c = null;
//处理数据
Map<String, Object> dataItem = null;
Object v = null;
for (int i=0, rownum = startIndex, len = (startIndex + dataList.size()); rownum < len; i++,rownum++){
r = hssfSheet.createRow(rownum);
r.setHeightInPoints(16);
dataItem = dataList.get(i);
for(int j=0, jlen =headInfoList.size(); j < jlen; j++){
headInfo = headInfoList.get(j);
c = r.createCell(j);
v = dataItem.get(headInfo.get("dataKey").toString());
if (v instanceof String) {
c.setCellValue((String)v);
}else if (v instanceof Boolean) {
c.setCellValue((Boolean)v);
}else if (v instanceof Calendar) {
c.setCellValue((Calendar)v);
}else if (v instanceof Double) {
c.setCellValue((Double)v);
}else if (v instanceof Integer
|| v instanceof Long
|| v instanceof Short
|| v instanceof Float) {
c.setCellValue(Double.parseDouble(v.toString()));
}else if (v instanceof HSSFRichTextString) {
c.setCellValue((HSSFRichTextString)v);
}else {
if(v!=null){
c.setCellValue(v.toString());
}
}
}
}
}
public void write2FilePath(HSSFWorkbook hssfWorkbook, String filePath) throws IOException{
FileOutputStream fileOut = null;
try{
fileOut = new FileOutputStream(filePath);
hssfWorkbook.write(fileOut);
}finally{
if(fileOut != null){
fileOut.close();
}
}
}
}
package com.bistone.websurvey.Lasting;
import com.bistone.utils.Utils;
public class ConstantDefinition {
//上传路径
public static final String SAVEPATH = Utils.getTruePath()+"framework/upload/";
}
package com.bistone.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import sun.text.normalizer.IntTrie;
import com.bistone.websurvey.bean.OperatorLogDto;
import com.bistone.websurvey.service.OperatorLogService;
import common.quickvalid.validators.int_range;
public class Utils {
public static String getTruePath() {
File f = new File(Utils.class.getResource("/").getPath());
String path = f.getPath();
path = notNull(path);
int index = path.indexOf("WEB-INF");
if (index > 0) {
return path.substring(0, index).replace("\\", "/");
} else {
return path.replace("\\", "/");
}
}
}
//需要的jar包
poi-3.8-20120326.jar