由於項目的需要做過VB版的上傳excel,vb.net,以及c#的上傳excel,現在做Java項目也同樣遇到了,爲了解決異構系統或者整理原始數據時無法避免的會用到這個東東,所以這樣的功能算是非常常見的。這篇博客將更深入的分享如何下載excel模板以及上傳excel文件。
Controller------導出excel模板
public void leadToExcel(HttpServletRequest request,
HttpServletResponse response) {
excelUtil = new ExcelUtil();
try {
// excel表格的表頭,map
LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
fieldMap.put("studentCode", "學號");
fieldMap.put("studentName", "學生姓名");
fieldMap.put("teachClass", "班級名稱");
fieldMap.put("dailyResult", "平時成績");
String sheetName = "平時成績";
// 導出模板
excelUtil.leadToExcel(fieldMap, sheetName, response);
} catch (Exception e) {
e.printStackTrace();
}
}
工具類excelUtil.leadToExcel
/**
* 導出Excel模板
*
* @param fieldMap
* 類的英文屬性和Excel中的中文列名的對應關係
* @param sheetName
* 工作表的名稱
* @param response
* 使用response可以導出到瀏覽器
* @throws ExcelException
* 異常
*/
public <T> void leadToExcel(LinkedHashMap<String, String> fieldMap,
String sheetName, HttpServletResponse response)
throws ExcelException {
// 設置默認文件名爲當前時間:年月日時分秒
String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
// 如果文件名沒提供,則使用時間戳
if (fileName == null || fileName.trim().equals("")) {
// 設置默認文件名爲當前時間:年月日時分秒
fileName = new SimpleDateFormat("yyyyMMddhhmmss")
.format(new Date()).toString();
}
// 設置response頭信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成輸出excel文件
response.setHeader("Content-disposition", "attachment; filename="
+ fileName + ".xls");
// 創建工作簿併發送到瀏覽器
try {
OutputStream out = response.getOutputStream();
int sheetSize = 65535;
// 創建工作簿併發送到OutputStream指定的地方
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
// 因爲2003的Excel一個工作表最多可以有65536條記錄,除去列頭剩下65535條
// 所以如果記錄太多,需要放到多個工作表中,其實就是個分頁的過程
// 1.計算一共有多少個工作表
// double sheetNum = Math.ceil(list.size()
// / new Integer(sheetSize).doubleValue());
double sheetNum = 1;
// 2.創建相應的工作表,並向其中填充數據
// 如果只有一個工作表的情況
if (1 == sheetNum) {
WritableSheet sheet = wwb.createSheet(sheetName, 1);
// 定義存放英文字段名和中文字段名的數組
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充數組
int count = 0;
for (Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
// 填充表頭
for (int i = 0; i < cnFields.length; i++) {
Label label = new Label(i, 0, cnFields[i]);
sheet.addCell(label);
}
// 設置自動列寬
setColumnAutoSize(sheet, 5);
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,則直接拋出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否則將其它異常包裝成ExcelException再拋出
} else {
throw new ExcelException("導出Excel失敗");
}
}
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,則直接拋出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否則將其它異常包裝成ExcelException再拋出
} else {
throw new ExcelException("導出Excel失敗");
}
}
}
Controller導入excel文件
/**
* 導入
*
* @author 劉新陽
* @version 1.0.0 , 2016年3月30日15:51:51
* @return
*/
@RequestMapping(value = "importDailyResult", method = RequestMethod.POST)
public void importDailyResult(HttpServletResponse response,
HttpServletRequest request) throws Exception {
// 創建一個通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
InputStream inExcelFile = null;
String dataBaseName = "itoo_basic";
// 判斷 request 是否有文件上傳,即多部分請求
if (multipartResolver.isMultipart(request)) {
// 轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 記錄上傳過程起始時的時間,用來計算上傳時間
int pre = (int) System.currentTimeMillis();
// 取得上傳文件
MultipartFile file = multiRequest.getFile(iter.next());
try {
inExcelFile = file.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 創建一個list 用來存儲讀取的內容
List list = new ArrayList();
Workbook rwb = null;
Cell cell = null;
String result = "error";
// 獲取Excel文件對象
try {
rwb = Workbook.getWorkbook(inExcelFile);
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取文件的指定工作表 默認的第一個
Sheet sheet = rwb.getSheet(0);
// 行數(表頭的目錄不需要,從1開始)
for (int i = 0; i < sheet.getRows(); i++) {
// 創建一個數組 用來存儲每一列的值
String[] str = new String[sheet.getColumns()];
// 列數
for (int j = 0; j < sheet.getColumns(); j++) {
// 獲取第i行,第j列的值
cell = sheet.getCell(j, i);
str[j] = cell.getContents();
}
// 把剛獲取的列存入list
list.add(str);
}
List studentList = new ArrayList();
List teachClassList = new ArrayList();
List studentResult = new ArrayList();
String teachCode= (String) request.getSession().getAttribute("name");
//"1240364";
String teacherId =questionBean.QueryTeachid(dataBaseName, teachCode) ;
List<StudentResult>studentResultlist=new ArrayList<StudentResult>();
String termId=request.getParameter("termId");
if (list.size() > 0) {
for (int i = 1; i < list.size(); i++) {
StudentResult studentResultEntity= new StudentResult();
Object[] o = (Object[]) list.get(i);
String studentCode = o[0].toString();
String teachClassName = o[2].toString();
String dailyResult = o[3].toString();
// 1.判斷學生表中是否存在該學號。根據學生學號查詢學生id
studentList = studentResultBean.querystudentId(dataBaseName,
studentCode);
if (studentList.size() > 0) {
String StudentId = studentList.get(0).toString();
// 2.判斷上課班中是否存在該上課班名稱,並根據上課班名稱查詢上課班id
teachClassList = studentResultBean.queryteachClassId(
dataBaseName, teachClassName);
// 3.根據學生id和上課班id判斷學生成績表中是否已經存在該學生在該上課班的成績,如果存在刪提示,如果不存在則插入
if (teachClassList.size() > 0) {
String teachClassId = teachClassList.get(0).toString();
//4.根據學年id,上課班id,教師id查詢成績規則id
String resultRuleId=studentResultBean.queryResultId(dataBaseName, termId, teachClassId, teacherId);
studentResult = studentResultBean
.queryStudentByStudentIdandTeachClassId(
dataBaseName, teachClassId, StudentId);
if (studentResult.size()== 0) {
// 5.將學生和上課班以及平時成績加入到學生成績實體。
studentResultEntity.setStudentId(StudentId);
studentResultEntity.setTeachClassId(teachClassId);
studentResultEntity.setDaliyResult(dailyResult);
studentResultEntity.setRemark("未判分");
studentResultEntity.setOperator("lxy");
studentResultEntity.setDataBaseName(dataBaseName);
studentResultEntity.setResultRuleId(resultRuleId);
studentResultlist.add(studentResultEntity);
}
}
}
}
boolean flag= studentResultBean.saveStudenResult(studentResultlist);
if (flag) {
result = "success";
}
}
JacksonJsonUntil jacksonJsonUntil = new JacksonJsonUntil();
jacksonJsonUntil.beanToJson(response, result);
}