Technical --POI derived class java package 3

1. 3 can be regarded as templates: a, based on the two templates template, derived more disposable Table
2. Package class instance:

public class ExportExcelTemplate3<T> {
	/**
	 * @param title
	 *            表格标题
	 * @param headers
	 *            头部标题集合
	 * @param dataset
	 *            数据集合
	 * @param out
	 *            输出流
	 */
	public void exportExcel(String[] titleName, String[] rowHeaders, String[] cellHeaders, Collection<T> dataset,
			String fileRealPath) {
		exportExcel2007(titleName, rowHeaders, cellHeaders, dataset, fileRealPath, "yyyy-MM-dd HH:mm:ss");
	}
	
	/*public void exportExcel(String[] titleName, String[] rowHeaders, String[] cellHeaders, Collection<T> dataset,
			HttpServletResponse response,HttpServletRequest request) {
		exportExcel2007(titleName, rowHeaders, cellHeaders, dataset, response,request ,"yyyy-MM-dd HH:mm:ss");
	}*/

	@SuppressWarnings({ "unchecked", "resource", "rawtypes" })
	private void exportExcel2007(String[] titleName, String[] rowHeaders, String[] cellHeaders, Collection<T> dataset,String fileRealPath,String pattern) {

		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		int sheetnum = titleName.length;
		for (int m = 0; m < sheetnum; m++) {
			// 生成一个表格
			XSSFSheet sheet = workbook.createSheet();
			String msg = titleName[m];
			try {
				String str = new String(msg.getBytes("UTF-8"), "UTF-8");
				workbook.setSheetName(m, str);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			
			// 生成一个样式
			XSSFCellStyle style = workbook.createCellStyle();
			// 设置背景色
			style.setFillForegroundColor((short) 13);
			style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
			// 设置边框
			style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			style.setBorderRight(XSSFCellStyle.BORDER_THIN);
			style.setBorderTop(XSSFCellStyle.BORDER_THIN);
			// 设置居中
			style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			// 生成一个字体
			XSSFFont font = workbook.createFont();
			font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
			font.setFontName("宋体");
			font.setColor(new XSSFColor(java.awt.Color.BLUE));
			font.setFontHeightInPoints((short) 11);
			// 把字体应用到当前的样式
			style.setFont(font);
			// 设置自动换行
			style.setWrapText(true);

			// 生成并设置另一个样式
			XSSFCellStyle style2 = workbook.createCellStyle();
			style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
			style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
			style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
			style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
			// 生成另一个字体
			XSSFFont font2 = workbook.createFont();
			font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
			// 把字体应用到当前的样式
			style2.setFont(font2);
			
			// 产生表格标题行
			XSSFRow row = sheet.createRow(0);
			XSSFCell cell;
			for (int i = 0; i < rowHeaders.length; i++) {
				cell = row.createCell(i + 1);// 标题行的单元格索引从1开始
				cell.setCellStyle(style);
				cell.setCellValue(new XSSFRichTextString(rowHeaders[i]));
			}
			// 产生表格标题列
			for (int j = 1; j <= cellHeaders.length; j++) {
				XSSFRow rownum = sheet.createRow(j);
				cell = rownum.createCell(0);// 获取第一个单元格(首列)
				cell.setCellStyle(style);
				cell.setCellValue(new XSSFRichTextString(cellHeaders[j - 1]));
			}
			// 遍历集合数据,产生数据行
			Iterator<T> it = dataset.iterator();
			int index = 0;
			T t;
			// 反射类
			Field[] fields;
			Field field;
			XSSFRichTextString richString;
			Pattern p = Pattern.compile("^//d+(//.//d+)?$");
			Matcher matcher;
			String fieldName;
			String getMethodName;
			Class tCls;
			Method getMethod;
			Object value;
			String textValue;
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			while (it.hasNext()) {
				index++;
				row = sheet.createRow(index);
				t = (T) it.next();
				// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
				fields = t.getClass().getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					cell = row.createCell(i + 1);
					cell.setCellStyle(style2);
					field = fields[i];
					fieldName = field.getName();
					getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

					try {
						tCls = t.getClass();
						getMethod = tCls.getMethod(getMethodName, new Class[] {});
						value = getMethod.invoke(t, new Object[] {});
						// 判断值的类型后进行强制类型转换
						textValue = null;
						if (value instanceof Integer) {
							cell.setCellValue((Integer) value);
						} else if (value instanceof Float) {
							textValue = String.valueOf((Float) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Double) {
							textValue = String.valueOf((Double) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Long) {
							cell.setCellValue((Long) value);
						}
						if (value instanceof Boolean) {
							textValue = "是";
							if (!(Boolean) value) {
								textValue = "否";
							}
						} else if (value instanceof Date) {
							textValue = sdf.format((Date) value);
						} else {
							// 其它数据类型都当作字符串简单处理
							if (value != null) {
								textValue = value.toString();
							}
						}
						if (textValue != null) {
							matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else {
								richString = new XSSFRichTextString(textValue);
								cell.setCellValue(richString);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}			
			/*try {
				// 设置下载时客户端Excel的名称
				response.setContentType("application/octet-stream;charset=utf-8");
				response.setHeader("Content-Disposition","attachment;filename=" + new String(titleName[m].getBytes(), "iso-8859-1") + ".xlsx");
				OutputStream ouputStream = response.getOutputStream();
				workbook.write(ouputStream);
				ouputStream.flush();
				ouputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			try {
				FileOutputStream fos = new FileOutputStream(fileRealPath);
				workbook.write(fos);
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

3. Call wrapper class instance:

// 导出Excel
	@RequestMapping(value = "/find", method = RequestMethod.GET)
	@ResponseBody
	public String ExportExcelInfo1(HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		 //sheet名称
		String[] titleName = {"水文表","数据表","环境表"};
       // excel标题表头
     		String[] titles0 = { "1时", "2时", "3时", "4时", "5时", "6时", "7时", "8时", "9时", "10时", "11时", "12时", "13时", "14时",
     				"15时", "16时", "17时", "18时", "19时", "20时", "21时", "22时", "23时", "24时" };
     		String[] celles0 = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
     				"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
		// 调用封装类
		ExportExcelTemplate2<User> util = new ExportExcelTemplate2<User>();
		List<User> list = new ArrayList<User>();
		util.exportExcel(titleName, titles0, celles0, list, "D://sheet.xls");
		return "D://sheet.xls";
}1)这样一次就可以导出三张sheet表:水文表,数据表,环境表
(2)这三张表的样式一样,都是首行,首列固定!
Published 143 original articles · won praise 10 · views 7538

Guess you like

Origin blog.csdn.net/qq591009234/article/details/103771834