(新手筆記分享)Spring MVC根據查詢生成Excel(純導出數據 及 導出數據+圖片) 返回地址給前端下載- 摘取片段,僅供參考

圖片:

 

 控制層:

	@ResponseBody
	@RequestMapping(value = "queryInfoBydateAndvillageName")
	public Map<String, Object> queryInfoBydateAndvillageName(HttpServletRequest request, String sDate, String eDate, String villageName, Authentication authentication) {
		Map<String, Object> result = new HashMap<String, Object>();
		SessionUser sessionUser = (SessionUser) authentication.getPrincipal();
		//ljCheckInstanceM是實體類
List<ljCheckInstanceM> resultPhotoList = dailyInService.queryPhotoInfoBydateAndvillageName(sDate, eDate, villageName, sessionUser.getLevel(), sessionUser.getId());
		//導出彙總記錄
		Map<String, String> fileQD = ExportExcelUtil.putInto2Excel(request.getServletContext(), null, resultPhotoList);
		String excelPathQD = fileQD.get("path");
		String excelNameQD = fileQD.get("name");
		//導出圖片
		Map<String, String> fileInfoPicture = ExportExcelUtil.putIntoExcel(request.getServletContext(), null, resultPhotoList);
		String excelPathP = fileInfoPicture.get("path");
		String excelNameP = fileInfoPicture.get("name");
		result.put("resultList", resultPhotoList);//結果集
		result.put("excelPathQD", "../" + excelPathQD);//路徑
		result.put("excelNameQD", excelNameQD);//Excel名稱
		result.put("excelPathPicture", "../" + excelPathP);//路徑
		result.put("excelNamePicture", excelNameP);//Excel名稱
		return result;
	}

 

生成Excel工具類: 

package com.cyl.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.cyl.model.ljCheckBodyTarget;
import com.cyl.model.ljCheckInstanceM;

public class ExportExcelUtil {

	private static Logger log = Logger.getLogger(ExportExcelUtil.class);

	/**
	 * 導出Excel,純導出數據
	 * 
	 * @param context
	 *            上下文會話對象
	 * @param dicument
	 *            生成文件的目錄文件名,參數為空時默認為excel
	 * @param list
	 *            Unallowable類數據集
	 * @return path返回路徑;name文件名;
	 */
	public static Map<String, String> putInto2Excel(ServletContext context, String dicument,
			List<ljCheckInstanceM> list) {
		Map<String, String> result = new HashMap<String, String>();
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet();
		XSSFRow row = sheet.createRow(0);
		FileOutputStream out = null;
		String fileName = TUtil.format("yyyy_MM_dd_HHmmssSSSSSS");
		fileName += ".xlsx";
		String filePath = null;
		try {
			row = sheet.createRow(0);
			//表頭
			row.createCell(0).setCellValue("ID");
			row.createCell(1).setCellValue("檢查頻率");
			row.createCell(2).setCellValue("檢查月份");
			row.createCell(3).setCellValue("檢查時間");
			row.createCell(4).setCellValue("小區名稱");
			row.createCell(5).setCellValue("鎮/街道");
			row.createCell(6).setCellValue("評分結果");
			row.createCell(7).setCellValue("提交人");
			// 日期格式轉爲字符串輸出
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			int rowIndex = 0;//寫入行下標
			int idMark = Integer.MIN_VALUE;//標記寫到了哪個小區
			for (int i = 1; i <= list.size(); i++) {
				ljCheckInstanceM data = list.get(i - 1);
				if (data.getId() != idMark) {//數據去重處理
					rowIndex++;
					row = sheet.createRow(rowIndex);
					row.createCell(0).setCellValue(data.getId());
					row.createCell(1).setCellValue(data.getFrequency());
					row.createCell(2).setCellValue(data.getSeq());
					
					String endTIme = sdf.format(data.getCheckDate());
					row.createCell(3).setCellValue(endTIme);
					
					row.createCell(4).setCellValue(data.getAttr1());
					row.createCell(5).setCellValue(data.getAttr2());
					row.createCell(6).setCellValue(data.getTotalScore());
					row.createCell(7).setCellValue(data.getAttr3());
				}
				
				idMark = data.getId();
			}
			String mes = context.getRealPath("/");
			String relpath = (StringUtils.isBlank(dicument) ? "excel" : dicument) + "/";
			filePath = mes + relpath;// 文件存放路徑
			File fileDir = new File(filePath);
			if (!(fileDir.exists() && fileDir.isDirectory())) {
				new File(filePath).mkdirs();
			}
			result.put("path", relpath);
			result.put("name", fileName);
			out = new FileOutputStream(filePath + fileName);
			wb.write(out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;// 返回下載結果
	}

	/**
	 * 導出Excel, 導出數據+圖片
	 * 
	 * @param context
	 *            上下文會話對象
	 * @param dicument
	 *            生成文件的目錄文件名,參數為空時默認為excel
	 * @param list
	 *            Unallowable類數據集
	 * @return path返回路徑;name文件名;
	 */
	public static Map<String, String> putIntoExcel(ServletContext context, String dicument,
			List<ljCheckInstanceM> list) {
		Map<String, String> result = new HashMap<String, String>();
		XSSFWorkbook wb = new XSSFWorkbook();
		XSSFSheet sheet = wb.createSheet();
		XSSFRow row = sheet.createRow(0);
		FileOutputStream out = null;
		String fileName = TUtil.format("yyyy_MM_dd_HHmmssSSSSSS");
		fileName += ".xlsx";
		String mes = context.getRealPath("/");
		String filePath = null;
		BufferedImage bufferImg = null;
		try {
			row = sheet.createRow(0);
			row.createCell(0).setCellValue("檢查頻率");
			row.createCell(1).setCellValue("檢查月份");
			row.createCell(2).setCellValue("檢查時間");
			row.createCell(3).setCellValue("小區名稱");
			row.createCell(4).setCellValue("鎮/街道");
			row.createCell(5).setCellValue("圖片");
			// 日期格式轉爲字符串輸出
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			int rowIndex = 0;//寫入行下標
			int imgColIndex = 5;//寫入照片列
			int idMark = Integer.MIN_VALUE;//標記寫到了哪個小區
			for (int i = 1; i <= list.size(); i++) {
				ljCheckInstanceM data = list.get(i - 1);
				if(data.getId() != idMark) {
					rowIndex++;
					imgColIndex = 5;
					row = sheet.createRow(rowIndex);
					//表頭
					row.createCell(0).setCellValue(data.getFrequency());
					row.createCell(1).setCellValue(data.getSeq());
					String endTIme = sdf.format(data.getCheckDate());
					row.createCell(2).setCellValue(endTIme);
					row.createCell(3).setCellValue(data.getAttr1());
					row.createCell(4).setCellValue(data.getAttr2());
					row.setHeight((short)1500);//設置行高度
				}
				//塞入圖片
				if (data.getAttr4() != null && !data.getAttr4().equals("")) {
					// 先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
					try {
						String file = mes + data.getAttr4();//獲取地址
						bufferImg = ImageIO.read(new File(file));
					} catch (IOException e) {
						e.printStackTrace();
					}
					try {
						ImageIO.write(bufferImg, "png", byteArrayOut);
					} catch (IOException e) {
						e.printStackTrace();
					}
					XSSFDrawing patriarch = sheet.createDrawingPatriarch();
					//8個參數解釋:  下面說的座標是cell內座標, cell中左上角爲(x,y)->(0,0)位置
					//dx1 圖片左上角所在x座標  (起始cell)
					//dy1 圖片左上角所在y 座標  (起始cell)
					//dx2 圖片右下角所在x座標 (結束cell)
					//dy2 圖片右下角所在y座標 (結束cell)
					//col1 圖片起始cell所在的列
					//row1 圖片起始cell所在的行
					//col2 圖片結束cell所在的列
					//row2 圖片結束cell所在的行
					//下面圖片左上角位於是第i行第7列, 右下角位於第i+1行第8列
					XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, imgColIndex, rowIndex, imgColIndex + 1, rowIndex + 1);
					// 插入圖片
					patriarch.createPicture(anchor,
							wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
					sheet.setColumnWidth(imgColIndex, 256 * 20);//列寬
					imgColIndex++;
				}
				idMark = data.getId();
			}
			String relpath = (StringUtils.isBlank(dicument) ? "excel" : dicument) + "/";
			filePath = mes + relpath;// 文件存放路徑
			File fileDir = new File(filePath);
			if (!(fileDir.exists() && fileDir.isDirectory())) {
				new File(filePath).mkdirs();
			}
			result.put("path", relpath);
			result.put("name", fileName);
			out = new FileOutputStream(filePath + fileName);
			wb.write(out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;// 返回下載結果
	}
}

基礎類:

package com.cyl.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

/**
 * 基礎類
 * 
 * @author Qiang1_Zhang
 */
public class TUtil {
	static Logger log = Logger.getLogger(TUtil.class);

	/**
	 * 日期轉換函數
	 * 
	 * @param format
	 *            需要轉換的格式
	 * @return 轉換後的日期
	 */
	public static String format(String format) {

		return new SimpleDateFormat(format).format(new Date());
	}

	/**
	 * 日期轉換函數
	 * 
	 * @param format
	 *            需要轉換的格式
	 * @return 轉換後的日期
	 */
	public static String format(Date date, String format) {
		return new SimpleDateFormat(format).format(date);
	}

	/**
	 * 打印函數
	 * 
	 * @param str
	 *            對象類型
	 */
	public static void print(Object str) {
		System.out.println(str);
	}

	/**
	 * 計算距今指定天數的日期
	 * 
	 * @param day
	 *            相差的天數,可爲負數
	 * @return 計算之後的日期
	 */
	public static String GetDay(int day) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		cal.setTime(new Date());// 設置日曆時間
		cal.add(Calendar.DAY_OF_MONTH, day);// 天數
		String strDate = sdf.format(cal.getTime());// 得到你想要的天數

		return strDate;
	}

	/**
	 * 獲取報表模板路徑
	 * 
	 * @return
	 */
	public static String getURL() {
		String dir = System.getProperty("user.dir");
		print("dir=" + dir);
		dir = dir.substring(0, dir.lastIndexOf("\\"));
		String filePath = dir;
		return filePath;
	}

	/**
	 * String類型日期轉換爲長整型
	 * 
	 * @param date
	 *            String類型日期
	 * @param format
	 *            日期格式
	 * @return long
	 */
	public static long strDateToLong(String date, String... format) {
		String format1 = null;
		if (format.length != 0) {
			format1 = format[0];
		} else {
			format1 = "yyyy-MM-dd HH:mm:ss";
		}
		String sDt = date;
		SimpleDateFormat sdf = new SimpleDateFormat(format1);
		long lTime = 0;
		try {
			Date dt2 = sdf.parse(sDt);
			lTime = dt2.getTime();
			print(lTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return lTime;
	}

	public static void longToString(long l) {
		format("");
	}

	/**
	 * 獲取文件創建時間
	 * 
	 * @param file
	 *            文件目錄
	 */
	public static String getCreateTime(File file) {
		// file = new File("e:/1.xls");
		String date = "";
		// file.lastModified();
		try {
			Process process = Runtime.getRuntime().exec(
					"cmd.exe /c dir " + file.getAbsolutePath() + "/tc");
			InputStream is = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			for (int i = 0; i < 5; i++) {// 前五行是其他的信息
				br.readLine();
			}
			String createDateLine = br.readLine();
			StringTokenizer tokenizer = new StringTokenizer(createDateLine);
			date = tokenizer.nextToken() + " " + tokenizer.nextToken();
			br.close();
			// print(date);
		} catch (IOException e) {
			log.error("" + e.getMessage());
		}
		return date;
	}

	/**
	 * 獲取文件最後修改時間
	 * 
	 * @param filePath
	 *            文件目錄
	 */
	public static void getLastModifyTime(File filePath) {
		filePath = new File(
				"\\\\10.131.18.8\\rt3生產機種\\ProductionReprot\\TraceAlterReprot-reprot");
		File[] list = filePath.listFiles();
		// for(File file : list){
		// print(file.getAbsolutePath()+"\tcreate time:"+getCreateTime(file));
		// }
		for (File file : list) {
			Date date = new Date(file.lastModified());
			print(format(date, "yyyy-MM-dd"));
		}
	}

	public static void getFile() {
		String root = "\\\\10.131.18.8\\rt3生產機種\\ProductionReprot";
		File filePath = new File(root);
		File[] list = filePath.listFiles();
		for (File file : list) {
			print(file.getName()
					+ "\t"
					+ new File(file.getAbsolutePath() + "\\"
							+ TUtil.format("yyyy-MM-dd") + ".xls").exists());
		}
	}

	static void test() {
		String today = TUtil.format("yyyy-MM-dd");
		String dest = ReadProperties.ReadProprety("server.report.path")
				+ "TraceAlterReprot-reprot" + "\\" + today + "\\";
		print(dest);
		File dir = new File(dest);// 創建當天目錄
		if (!dir.exists()) {
			dir.mkdir();
		}
	}

	public static void getTimeDifference() {
		try {
			Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-09-15");

			Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse("2014-09-14");
			print((d2.getTime() - d1.getTime()) / 1000 / 60 / 60 / 24);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public List<String> distinctList(List<String> list) {
		HashSet<String> h = new HashSet<String>(list);
		list.clear();
		list.addAll(h);
		return list;
	}
	
	public List<Object> removeDuplicate(List<Object> list) {
		HashSet<Object> h = new HashSet<Object>(list);
		list.clear();
		list.addAll(h);
		return list;
	}
	
	/**
	 * 獲取四捨五入的整數
	 * @param input 乘數
	 * @param rate 比率
	 * @return 取整後的結果
	 */
	public double getRound(int input,double rate){
		double tmp = input * rate;
		return Math.round(tmp);
	}
	
	/**
	 * 獲取四捨五入的整數
	 * @param input 乘數
	 * @param rate 比率
	 * @return 取整後的結果
	 */
	public double ceil(int input,double rate){
		double tmp = input * rate;
		return Math.ceil(tmp);
	}
}

前端 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
            <!-- 片段 -->
            <div class="cl pd-5 bg-1 bk-gray mt-20">
			<span class="l">
				<a class="btn btn-primary radius" data-title="導出彙總記錄" id="downloadExcelQueryData" href="javascript:;"><i class="Hui-iconfont">&#xe600;</i> 導出彙總記錄</a>
			</span>
					
			<span class="l" style="margin-left: 10px">
				<a class="btn btn-primary radius" data-title="導出明細圖片" id="downloadExcelPicture" href="javascript:;"><i class="Hui-iconfont">&#xe600;</i> 導出圖片</a>
			</span>
			<span class="r" id="flushTime"></span>
	    </div>
	</body>
	<script>
		 /**
		* 提供片段
		* 
		*/
		function queryInfo() {
			//省略獲取參數...
            //請求
			$.ajax({
				type: 'post',
				url: '<%=basePath%>inspection/queryInfoBydateAndvillageName.cyl',
				dataType: 'json',
				data: {
					sDate: logmin,
					eDate: logmax,
					villageName: compname
				},
				success: function(data) {
					console.log(data)
					setDownloadButton("downloadExcelQueryData",data.excelPathQD, data.excelNameQD);//設置下載地址
					setDownloadButton("downloadExcelPicture", data.excelPathPicture, data.excelNamePicture);//設置下載地址
					
				},
				error: function() {
					layer.alert("查詢失敗"); 
				}
			});
		}
        
        //下載地址
        function setDownloadButton(id, path, name) {
			var downloadButton = $("#"+ id)[0];
			if (path == null || name == null || typeof (path) == "undefined"
					|| typeof (name) == "undefined")
				downloadButton.setAttribute("href", "#");
			else
				downloadButton.setAttribute("href", ""+ path +""+ name  +"");
		}
		
	</script>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章