1、基本可以通用的工具类
package com.idcsol.apps.common.excel;
import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; 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.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.util.Region;
@SuppressWarnings("deprecation")public class ExportExcel{ //显示的导出表的标题 private String title; //导出表的列名 private String[] rowName ; private List<Object[]> dataList = new ArrayList<Object[]>(); HttpServletResponse response; //构造方法,传入要导出的数据 public ExportExcel(String title,String[] rowName,List<Object[]> dataList,HttpServletResponse response){ this.dataList = dataList; this.rowName = rowName; this.title = title; this.response = response; } /* * 导出数据 * */ public void export() throws Exception{ try{ HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 HSSFSheet sheet = workbook.createSheet(title); // 创建工作表 // 产生表格标题行 HSSFRow rowm = sheet.createRow(0); HSSFCell cellTiltle = rowm.createCell(0); //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象 HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); cellTiltle.setCellStyle(columnTopStyle); cellTiltle.setCellValue(title); // 定义所需列数 int columnNum = rowName.length;
HSSFRow row2 = sheet.createRow(2); HSSFRow rowRowName = sheet.createRow(3); // 在索引2的位置创建行(最顶端的行开始的第二行)
//根据自己的需要合并单元格 sheet.addMergedRegion(new Region(2,(short)0,3,(short)0));//(四个参数分别是)合并开始行,合并开始列,合并结束行,合并结束列 sheet.addMergedRegion(new Region(2,(short)1,3,(short)1)); sheet.addMergedRegion(new Region(2,(short)2,3,(short)2)); sheet.addMergedRegion(new Region(2,(short)3,3,(short)3)); sheet.addMergedRegion(new Region(2,(short)4,2,(short)6)); sheet.addMergedRegion(new Region(2,(short)7,3,(short)7)); sheet.addMergedRegion(new Region(2,(short)8,2,(short)9)); sheet.addMergedRegion(new Region(2,(short)10,3,(short)10)); sheet.addMergedRegion(new Region(2,(short)11,3,(short)11)); sheet.addMergedRegion(new Region(2,(short)12,3,(short)12));
// 将列头设置到sheet的单元格中 for(int n=0;n<columnNum;n++){ HSSFCell cellRowName = null; //创建列头对应个数的单元格 HSSFCell cellRowNamei_n = null; //创建列头对应个数的单元格 if(n < 4 || n==7 || n>9){ cellRowName = row2.createCell(n); cellRowNamei_n = rowRowName.createCell(n); }else{ cellRowName = rowRowName.createCell(n); cellRowNamei_n = row2.createCell(n); if (n==4) { cellRowNamei_n.setCellValue("任(兼职状况)"); }else if (n==8){ cellRowNamei_n.setCellValue("资格种类"); } } cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型 HSSFRichTextString text = new HSSFRichTextString(rowName[n]); cellRowName.setCellValue(text); //设置列头单元格的值 cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 cellRowNamei_n.setCellStyle(columnTopStyle); } //将查询出的数据设置到sheet对应的单元格中 for(int i=0;i<dataList.size();i++){ Object[] obj = dataList.get(i);//遍历每个对象 HSSFRow row = sheet.createRow(i+4);//创建所需的行数 for(int j=0; j<obj.length; j++){ HSSFCell cell = null; //设置单元格的数据类型 if(j == 0){ cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(i+1); }else{ cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING); if(obj[j] != null){ cell.setCellValue(obj[j].toString()); //设置单元格的值 } } cell.setCellStyle(style); //设置单元格样式 } } //让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow currentRow; //当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { HSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { int length = 0; if (null != currentCell) { length = currentCell.getStringCellValue().getBytes().length; } if (columnWidth < length) { columnWidth = length; } } } } if(colNum == 0){ sheet.setColumnWidth(colNum, (columnWidth-2) * 256); }else{ sheet.setColumnWidth(colNum, (columnWidth+4) * 256); } } if(workbook !=null){ try { String fileName = title + ".xls"; fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); String headStr = "attachment; filename=\"" + fileName + "\""; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", headStr); OutputStream out = response.getOutputStream(); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } }catch(Exception e){ e.printStackTrace(); } } /* * 列头单元格样式 */ public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short)11); //字体加粗 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.BLACK.index); //设置左边框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.BLACK.index); //设置右边框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.BLACK.index); //设置顶边框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } /* * 列数据信息单元格样式 */ public HSSFCellStyle getStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 //font.setFontHeightInPoints((short)10); //字体加粗 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.BLACK.index); //设置左边框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.BLACK.index); //设置右边框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.BLACK.index); //设置顶边框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } }
2、控制器中的使用方法
public void exportPostState(@ModelAttribute Page<PostState> page, HttpSession httpSession,HttpServletResponse response) throws Exception { PostState postState=new PostState();//可以替换成需要的类// postState.setPostNo(orgId); User user = (User) httpSession.getAttribute("user"); Organization organization = new Organization(); String title = "聘岗信息";//可以替换成需要的文件名 if (! "1".equals(user.getRoletype())) { postState.setUnitNo(user.getUnitno()); organization = organizationService.selectByKey(user.getUnitno()); title = organization.getOrganizationName()+"-聘岗信息"; } page.setRows(500); List<PostState> list = postStateService.selectAll(page, postState).getRecords();//查询数据库中的相关数据 String[] rowsName = new String[]{"序号","姓名","岗位分类","所聘岗位名", "周课时","任课年级","所数学科","无任课备注","教师资格种类","学科", "现职称","年度考核","备注"}; //可以替换成需要的表头 List<Object[]> dataList = new ArrayList<Object[]>(); Object[] objs = null; for (int i = 0; i < list.size(); i++) { PostState post = list.get(i); objs = new Object[rowsName.length]; objs[0] = i; objs[1] = post.getPersonName() == null ? "":post.getPersonName(); objs[2] = post.getPostTypeName() == null ? "":post.getPostTypeName(); objs[3] = post.getPostName() == null ? "":post.getPostName(); objs[4] = post.getWorkload() == null ? "":post.getWorkload(); objs[5] = post.getGrade() == null ? "":post.getGrade(); objs[6] = post.getObjectName() == null ? "":post.getObjectName(); objs[7] = post.getOverworkRemarks() == null ? "":post.getOverworkRemarks(); objs[8] = post.getTeacherTypeName() == null ? "":post.getTeacherTypeName(); objs[9] = post.getTeacherObjectName() == null ? "":post.getTeacherObjectName(); objs[10] = post.getTitleName() == null ? "":post.getTitleName(); objs[11] = post.getCheckResultName() == null ? "":post.getCheckResultName(); objs[12] = post.getRemarks() == null ? "":post.getRemarks(); dataList.add(objs); } ExportExcel ex = new ExportExcel(title, rowsName, dataList,response); ex.export(); }
注:导出不能用ajax连接后台,否则不会弹出选择文件保存位置的框
需要导入poi的jar包
maven中pom的写法:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.8</version> <exclusions> <exclusion> <artifactId>commons-codec</artifactId> <groupId>commons-codec</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.8</version> </dependency>
转载于:https://www.cnblogs.com/mymission/p/5781015.html
相关资源:数据结构—成绩单生成器