将数据导出成excel文件

1、jar包
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8-beta5</version>
</dependency>

2、html代码

<input type="button" class="btn btn-success" id="exportPriceList" value="导出基准价列表"/>

3、后台代码

(1)、bean层

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.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * Excel工具类
 */
public class WorkbookUtil {
	// 表格的sheet 的名字不能多余31 个字符
	// 不能包含:: \ * ? / [ ]
	// 0x0000
	// 0x0003
	public static String createSafeSheetName(String sheetName) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < sheetName.length(); i++) {
			char c = sheetName.charAt(i);
			switch (c) {
			case ':':
			case '\\':
			case '*':
			case '?':
			case '/':
			case ']':
			case '[':
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}
	/**
	 * 创建单元格
	 * @param row
	 * @param num
	 * @param value
	 */
	public static void createCell(Row row ,int num,int value,CellStyle style){
		Cell cell = row.createCell(num);
		cell.setCellValue(value);
		cell.setCellStyle(style);
	}
	
	/**
	 * 创建单元格
	 * @param row
	 * @param num
	 * @param value
	 */
	public static void createCell(Row row ,int num,double value,CellStyle style){
		Cell cell = row.createCell(num);
		cell.setCellValue(value);
		cell.setCellStyle(style);
	}
	
	/**
	 * 创建单元格
	 * @param row
	 * @param num
	 * @param value
	 */
	public static void createCell(Row row ,int num,String value,CellStyle style){
		Cell cell = row.createCell(num);
		cell.setCellValue(value);
		cell.setCellStyle(style);
	}
	
	/**
	 * 合并单元格
	 * @param sheet
	 * @param firstRow
	 * @param lastRow
	 * @param firstCol
	 * @param lastCol
	 */
	public static CellRangeAddress mergeCell(Sheet sheet,int firstRow,int lastRow,int firstCol,int lastCol,CellStyle style){
		CellRangeAddress address = new CellRangeAddress(firstRow,lastRow,firstCol,lastCol);
		sheet.addMergedRegion(address);
		for (int i = address.getFirstRow(); i <= address.getLastRow(); i++) {
			HSSFRow row = (HSSFRow) sheet.getRow(i);
			if(row == null){
				row = (HSSFRow) sheet.createRow(i);
			}
			for (int j = address.getFirstColumn(); j <= address.getLastColumn(); j++) {
				HSSFCell cell = row.getCell(j);
				if(cell == null){
					cell = row.createCell(j);
				}
				cell.setCellStyle(style);
			}
		}
		
		return address;
	}
	
	public static void createTitle(Row row,Workbook wb,CellStyle style,String[] title) {
		for (int i = 0; i <title.length;i++) {
			createCell(row, i, title[i], style);
		}
	}
	public static HSSFCellStyle createContentStyle(HSSFWorkbook wb){
		//设置字体
		HSSFFont font = wb.createFont();
	    font.setColor(HSSFColor.BLACK.index);
	    font.setFontHeightInPoints((short) 10);
	    font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

		HSSFCellStyle style = wb.createCellStyle();
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
		style.setFont(font);
		return style;
	}
	public static HSSFCellStyle createTitleStyle(HSSFWorkbook wb){
		//设置字体
		HSSFFont font = wb.createFont();
	    font.setColor(HSSFColor.VIOLET.index);
	    font.setFontHeightInPoints((short) 10);
	    font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		
		//生成一个样式
		HSSFCellStyle style = wb.createCellStyle();
		
		
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setFont(font);
		return style;
	}
}

(2)、Controller层

@RequestMapping("exportPriceList")
public void exportPriceList(HttpServletRequest req, HttpServletResponse resp) throws Exception{
	resp.setContentType("text/plain; charset=UTF-8");
	Map<String,Object> queryMap = new HashMap<String,Object>();
	List<Map<String, Object>> listMap = this.newProductService.exportPriceList(queryMap);    //从数据库查询来的数据
	try {
             /**
               * 生成excel
               * 参数1:封装好的Map对象集合,对象中的字段类型不能有自定义类型的数据,否则无法解析生成excel
               * 参数2:excel的标题行
               * 参数3:Map对象中需要导出的字段
               */
               HSSFWorkbook wb = exportutil.exportMap(listMap, 
			new String[]{"ID", "名称", "性别", "年龄"},        
			new String[]{"id", "Name", "sex", "age"});        
		String fileName = com.yjw.util.DateUtil.dateToStr(new java.util.Date(), "yyyyMMddHHmmss");
		resp.setHeader("Content-disposition", "attachment; filename=" 
                        + java.net.URLEncoder.encode("文件导出", "UTF-8")
			+ fileName + ".xls");
		resp.setContentType("application/msexcel");
		resp.setCharacterEncoding("UTF-8");
		wb.write(resp.getOutputStream());
	} catch (Exception e) {
		e.printStackTrace();
	}
}

(3)、Util层

public class exportutil{
    public HSSFWorkbook exportMap(List<Map<String, Object>> objs, String[] titles, String[] fields) throws Exception{
		//行号
		int count = 0;
		//创建一个工作薄
		HSSFWorkbook wb = new HSSFWorkbook();
		//创建一个sheet
		HSSFSheet sheet = wb.createSheet();
		//创建一行
		HSSFRow row = sheet.createRow(count++); //这一行为第一行,即标题行
		
		//生成一个样式
		HSSFCellStyle style1 = WorkbookUtil.createContentStyle(wb);
		HSSFCellStyle style2 = WorkbookUtil.createTitleStyle(wb);
		HSSFCellStyle styleWrap = WorkbookUtil.createContentStyle(wb);
		styleWrap.setWrapText(true);
		
		//为标题行生成单元格
		for (int i = 0; i < titles.length; i++) {
			WorkbookUtil.createCell(row, i, ""+titles[i]+"", style2);
		}
		
		// 红色字体
		HSSFFont fontRed = wb.createFont();
		fontRed.setColor(HSSFColor.RED.index);
		
		//生成表格内容
		/////////////////////////
		boolean hasFields = !(fields == null || fields.length == 0); // 是否指定导出字段
		Map<String, Object> map = null;
		Set<Map.Entry<String, Object>> setEntry = null;
		for (int i = 0; i < objs.size(); i++) { 
			map = objs.get(i);
			if (null == map) {
				continue;
			}
			row = sheet.createRow(count++);
			int col = 0;
			// 根据指定字段导出
			if(hasFields) {
				for(String f : fields) {
					if(StringUtils.isEmpty(f)) {
						continue;
					}
					if(f.startsWith("<RichText>")) { // 字段名开头包含<RichText>时,按富文本处理
						Object obj = map.get(f);
						HSSFRichTextString rts = new HSSFRichTextString(obj == null ? "" : String.valueOf(obj));
						// *开头的每行文本字体用红色,主要针对质检单描述信息
						Pattern pattern = Pattern.compile("\\*[^\r\n]+");
						Matcher m = pattern.matcher(rts.getString());
						while(m.find()) {
							rts.applyFont(m.start(), m.end(), fontRed);
						}
						Cell cell = row.createCell(col++);
						cell.setCellValue(rts);
						cell.setCellStyle(styleWrap);
					} else if(map.get(f) == null) {
						WorkbookUtil.createCell(row, col++, "", style1);
					} else if (map.get(f).getClass().getName().equals("java.util.Date")) {  //java.util.Date类型数据
						WorkbookUtil.createCell(row, col++, DateUtil.dateToStr((java.util.Date) map.get(f),"yyyy-MM-dd"), style1);
					} else {
						WorkbookUtil.createCell(row, col++, String.valueOf(map.get(f)), style1);
					}
				}
			} else { // 导出所有字段
				setEntry = map.entrySet();
				for (Map.Entry<String, Object> e : setEntry) {
					if (null == e) {
						continue;
					}
					
					if(e.getValue() == null) {
						WorkbookUtil.createCell(row, col++, "", style1);
					} else if (e.getValue().getClass().getName().equals("java.util.Date")) {  //java.util.Date类型数据
						WorkbookUtil.createCell(row, col++, DateUtil.dateToStr((java.util.Date) e.getValue(),"yyyy-MM-dd"), style1);
					} else {
						WorkbookUtil.createCell(row, col++, String.valueOf(e.getValue()), style1);
					}
				}
			}
			objs.remove(i);
			i--;
			col = 0;
		}
		/////给每一列的单元格的size自适应,根据内容自动调整宽度和高度,但是对于中文的单元格无效,这个比较好性能
		for (int i = 0; i < titles.length; i++) {
			sheet.autoSizeColumn(i,true);	//让宽度根据内容长度自适应,中文情况下自适应不成立
		}
		
		for (int i = 0; i < titles.length; i++) {
			int  colWidth = sheet.getColumnWidth(i) / 256;		//得到单元格的实际宽度
			for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum ++) {
				if (null != sheet.getRow(rowNum)) {
					int length = sheet.getRow(rowNum).getCell(i).toString().getBytes().length;	//获取单元格内容的字节长度
					if (colWidth < length) {	//如果单元格的实际宽度小于单元格字节长度
						colWidth = length;		
					}
				}
			}
			
			sheet.setColumnWidth(i, 10*256);		//重新设置单元格宽度
			
		}
		
		return wb;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42187261/article/details/80499697