poi通過jsp+java實現Excel文件上傳和下載

jsp前臺代碼

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
$(document).ready(function(){
	$(function() {
		$('#importSubmit').click(function(){
			if(checkData()){
				$('#importForm').submit();
			}
		});
		//JS校驗form表單信息
		function checkData(){
			var fileDir = $("#importfile").val();
			var suffix = fileDir.substr(fileDir.lastIndexOf("."));
			if("" == fileDir){
				alert("請選擇需要導入的Excel文件!");
				return false;
			}
			if(".xls" != suffix && ".xlsx" != suffix ){
				alert("請選擇Excel格式的文件導入!");
				return false;
			}
			return true;
		}
	});
});
</script>

</head>
<body>
<div>
	<form method="post" enctype="multipart/form-data" id="importForm" action="url地址">
		<tr><td>上傳文件:
		<input id="importfile" type="file" name="importfile" />
		<input type="button" value="上傳" id="importSubmit" name="importSubmit" />
		</td></tr>
	/form>
/div>
</body>
</html>

java後臺代碼

class 中
// sheet名稱
private static String sheetName = "";

public void setSheetName(String sheetName) {
	this.sheetName = sheetName;
}

public String getSheetName() {
	return sheetName;
}

@RequestMapping("/前臺輸入的url")
public ModelAndView ajaxUploadExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {

	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

	InputStream in = null;
	// Excel數據
	List<List<Object>> dataList = null;
	MultipartFile file = multipartRequest.getFile("importfile");
	String fileName = file.getOriginalFilename();
	if (file.isEmpty()) {
		throw new Exception("文件不存在!");
	}

	in = file.getInputStream();
	dataList = getBankListByExcel(in, file.getOriginalFilename(), false);

	// 表名
	String sheetName = getSheetName();
	// 首行數據
	List<String> columnList = new ArrayList<String>();
	// 錯誤數據列表
	List<List<String>> errorList = new ArrayList<List<String>>();
	// 設置日期格式
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String create_date = df.format(new Date());

	for (int i = 0; i < dataList.size(); i++) {

		List<Object> cellList = dataList.get(i);
		if (cellList == null || cellList.size() == 0) {
			continue;
		}
		// 列名
		if (columnList.size() == 0) {
			for (Object object : cellList) {
				// 字段名格式化,去空格,中文括號
				String strObject = object.toString().replaceAll("\\s", "");
				strObject = strObject.replace("(", "(");
				strObject = strObject.replace(")", ")");
				columnList.add(strObject);
			}
		// 數據
		} else {
			if (cellList.contains("非法字符") || cellList.contains("未知類型")) {
				List<String> errRow = (List<String>)(List)cellList;
				errorList.add(errRow);
			}
			JSONObject jsonObject = new JSONObject();
			// json格式轉換失敗
			boolean isError = false;
			for (int j = 0; j < cellList.size(); j++) {
				try {
					jsonObject.put(columnList.get(j), cellList.get(j));
				} catch (Exception e) {
					isError = true;
				}
			}
			if (!isError) {
				jsonObject.put(CREATETIME, create_date);
				try {
					// 數據庫操作
				} catch (Exception e) {
					List<String> errRow = (List<String>)(List)cellList;
					if (errorList.size() == 0) {
						errorList.add(columnList);
					}
					errorList.add(errRow);
				}
			} else {
				// 錯誤數據行
				List<String> errRow = (List<String>)(List)cellList;
				if (errorList.size() == 0) {
					errorList.add(columnList);
				}
				errorList.add(errRow);
			}
		}
	}

	// 導入結果提示
	// 報錯則導出
	if (errorList.size() != 0) {
		createExcelForList(response, errorList, "存在導入失敗的數據,請查看Excel");
	}

	return null;
}

讀取Excel數據

/**
 * 描述:獲取IO流中的數據,組裝成List<List<Object>>對象
 * 
 * @param in,fileName
 * @return
 * @throws IOException
 */
public List<List<Object>> getBankListByExcel(InputStream in, String fileName, boolean isFirstRow) throws Exception {
	// sheet數據列表
	List<List<Object>> dataList = null;

	// 創建Excel工作薄
	Workbook work = this.getWorkbook(in, fileName);
	if (null == work) {
		throw new Exception("創建Excel工作薄爲空!");
	}
	Sheet sheet = null;
	Row row = null;
	Cell cell = null;

	dataList = new ArrayList<List<Object>>();

	sheet = work.getSheetAt(0);
	// sheet名稱
	setSheetName(sheet.getSheetName());
	// 遍歷當前sheet中的所有行
	for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
		row = sheet.getRow(j);
		if (row == null) {
			continue;
		}

		// 遍歷所有的列
		List<Object> cellList = new ArrayList<Object>();

		for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
			cell = row.getCell(y);
			cellList.add(this.getCellValue(cell));
		}
		dataList.add(cellList);
		if (isFirstRow) {
			return dataList;
		}

	}
	return dataList;
}
/**
 * 描述:根據文件後綴,自適應上傳文件的版本
 * 
 * @param inStr,fileName
 * @return
 * @throws Exception
 */
public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
	Workbook wb = null;
	String fileType = fileName.substring(fileName.lastIndexOf("."));
	if (excel2003L.equals(fileType)) {
		wb = new HSSFWorkbook(inStr); // 2003-
	} else if (excel2007U.equals(fileType)) {
		wb = new XSSFWorkbook(inStr); // 2007+
	} else {
		throw new Exception("解析的文件格式有誤!");
	}
	return wb;
}

/**
 * 描述:對錶格中數值進行格式化
 * 
 * @param cell
 * @return
 */
public static String getCellValue(Cell cell) {
	String cellValue = "";
	if (cell == null) {
		return cellValue;
	}
	// 判斷數據的類型
	switch (cell.getCellType()) {
	// 數字
	case Cell.CELL_TYPE_NUMERIC:
		// 處理日期格式、時間格式
		if (HSSFDateUtil.isCellDateFormatted(cell)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			Date date = cell.getDateCellValue();
			cellValue = sdf.format(date);
			// 處理數值格式
		} else if (cell.getCellStyle().getDataFormat() == 0) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			cellValue = String.valueOf(cell.getRichStringCellValue().getString());
		} else {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			cellValue = String.valueOf(cell.getRichStringCellValue().getString());
		}
		break;
	// 字符串
	case Cell.CELL_TYPE_STRING:
		cellValue = String.valueOf(cell.getStringCellValue());
		break;
	// Boolean
	case Cell.CELL_TYPE_BOOLEAN:
		cellValue = String.valueOf(cell.getBooleanCellValue());
		break;
	// 公式
	case Cell.CELL_TYPE_FORMULA:
		try {
			cellValue = String.valueOf(cell.getStringCellValue());
		} catch (IllegalStateException e) {
			DecimalFormat format = new DecimalFormat("0.##");
			cellValue = format.format(cell.getNumericCellValue());
		}
		break;
	// 空值
	case Cell.CELL_TYPE_BLANK:
		cellValue = "";
		break;
	// 故障
	case Cell.CELL_TYPE_ERROR: 
		cellValue = "非法字符";
		break;
	default:
		cellValue = "未知類型";
		break;
	}
	return cellValue;
}

excel導出功能

/**
 * 	導出Excel文檔
 * @param response
 * @param outputList 導出數據列表
 * @param fileName   導出文件名
 * @throws Exception
 */
public static void createExcelForList(HttpServletResponse response, List<List<String>> outputList, String fileName) throws Exception {

	// 創建XSSFWorkbook對象
	XSSFWorkbook wb = new XSSFWorkbook();
	// 創建XSSFSheet對象
	XSSFSheet sheet = wb.createSheet();

	for (int i = 0; i < outputList.size(); i++) {

		// 創建XSSFRow對象
		// 創建行
		XSSFRow row = sheet.createRow(i);
		// 獲取行數據
		List<String> cellList = outputList.get(i);
		for (int j = 0; j < cellList.size(); j++) {
			// 創建列
			XSSFCell cell = row.createCell(j);
			cell.setCellValue(cellList.get(j));
		}
	}
	// 固定首行
	sheet.createFreezePane( 0, 1, 0, 1 );
	// 列寬自適應
	for (int columnIndex = 0; columnIndex < outputList.get(0).size(); columnIndex++) {
		int columnWidth = sheet.getColumnWidth(columnIndex) / 256;
		for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
			XSSFRow currentRow;
			// 當前行未被使用過
			if (sheet.getRow(rowIndex) == null) {
				currentRow = sheet.createRow(rowIndex);
			} else {
				currentRow = sheet.getRow(rowIndex);
			}
			if (currentRow.getCell(columnIndex) != null) {
				XSSFCell currentCell = currentRow.getCell(columnIndex);
				if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
					int length = 0;
					try {
						length = currentCell.getStringCellValue().getBytes().length;
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (columnWidth < length) {
						columnWidth = length;
					}
				}
			}
		}

		sheet.setColumnWidth(columnIndex, (columnWidth) * 256);
	}
	// 輸出Excel文件
	try {

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
		// 文件類型
		response.setHeader("content-type", "application/vnd.ms-excel");
		// 文件默認名稱
		fileName = fileName + df.format(new Date()) + ".xlsx";
		response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
		wb.write(response.getOutputStream());
		System.out.println("---下載提示------:下載成功");
	} catch (IOException e) {
		e.printStackTrace();
		System.out.println("---下載提示------:下載失敗");
	}
}

以上就是Excel上傳保存數據庫跟錯誤數據導出Excel的所有代碼····

 

 

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