import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
String[] tableHeader = { "列1", "列2"};//指定列名
short cellNumber = (short) tableHeader.length;// 表的列数
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel
HSSFCell cell = null; // Excel的列
HSSFRow row = null; // Excel的行
HSSFCellStyle style = workbook.createCellStyle(); // 设置表头的类型
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCellStyle style1 = workbook.createCellStyle(); // 设置数据类型
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont font = workbook.createFont(); // 设置字体
HSSFSheet sheet = workbook.createSheet("sheet1"); // 创建一个sheet
try {
//如果list为空,表格输出"暂无数据"
if (list.size() < 1) {
row = sheet.createRow(0);
row.setHeight((short) 400);
cell = row.createCell(0);
cell.setCellValue("暂无数据");
}else{
row = sheet.createRow(0);
row.setHeight((short) 400);
for (int j = 0; j < cellNumber; j++) {
cell = row.createCell(j);// 创建第0行第k列
cell.setCellValue(tableHeader[j]);// 设置第0行第k列的值
sheet.setColumnWidth(j, 4000);// 设置列的宽度
font.setColor(HSSFFont.COLOR_NORMAL); // 设置单元格字体的颜色.
font.setFontHeight((short) 200); // 设置单元字体高度
style1.setFont(font);// 设置字体风格
cell.setCellStyle(style1);
}
for (int i = 0; i
Beanbean = list.get(i);// 获取student对象
row = sheet.createRow((short) (i + 1));// 创建第i+1行
row.setHeight((short) 400);// 设置行高
cell = row.createCell(0);// 创建第i+1行第0列,此为序列号
cell.setCellValue((i + 1));// 设置第i+1行第0列的值
cell.setCellStyle(style);// 设置风格
if(null!=bean.getRow1()){
cell = row.createCell(2);// 创建第i+1行第2列
cell.setCellValue(bean.getRow1());// 设置第i+1行第2列的值
cell.setCellStyle(style);// 设置风格
}
if(null!=bean.getRow2()){
cell = row.createCell(3);// 创建第i+1行第3列
cell.setCellValue(bean.getRow1());// 设置第i+1行第3列的值
cell.setCellStyle(style);// 设置风格
}
}
}
} catch (Exception e) {
logger.error("错误信息:" + e);
}
OutputStream out = null;// 创建一个输出流对象
try {
out = response.getOutputStream();
String headerStr = "new";//文件名
headerStr = new String(headerStr.getBytes("gb2312"), "ISO8859-1");// headerString为中文时转码
response.setHeader("Content-disposition", "attachment; filename="
+ headerStr + ".xls");// filename是下载的xls的名,建议最好用英文
response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
response.setHeader("Pragma", "No-cache");// 设置头
response.setHeader("Cache-Control", "no-cache");// 设置头
response.setDateHeader("Expires", 0);// 设置日期头
workbook.write(out);
out.flush();
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}