JSP匯入匯出Excel功能
阿新 • • 發佈:2018-11-13
匯入匯出功能需求是這樣的:按照條件查詢出結果,然後將這些結果以excel形式匯出;修改欄位資訊後(主鍵不允許修改)匯入即覆蓋原欄位資訊,完成更新。本例是藉助poi完成的,將poi-3.9.jar匯入到WEB-INF下的lib的資料夾,與此一起匯入的還有commons-io-1.3.2.jar,commons-fileupload-1.2.1.jar,用於io輸入和檔案上傳。
一、匯出
功能:選擇時間條件——匯出——選擇儲存路徑——儲存,如下圖所示
實現過程:寫一個建立excel的方法,先建立一個excel檔案,建立好工作表,表頭;然後將資料內容填充到裡面,資料是根據查詢的結果而來;最後儲存excel檔案至伺服器的一個臨時位置(每次會覆蓋),使用者下載的時候從這個位置下載到客戶端。
Excel建立程式碼:
public static void createExcel(List<Sku> list) throws SQLException{ // 建立一個Excel檔案 HSSFWorkbook workbook = new HSSFWorkbook(); // 建立一個工作表 HSSFSheet sheet = workbook.createSheet("sku表"); // 新增表頭行 HSSFRow hssfRow = sheet.createRow(0); // 設定單元格格式居中 HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 新增表頭內容 HSSFCell headCell = hssfRow.createCell(0); headCell.setCellValue("服務SKU"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(1); headCell.setCellValue("內外部判別"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(2); headCell.setCellValue("產品名稱"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(3); headCell.setCellValue("規格型號"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(4); headCell.setCellValue("發票名稱"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(5); headCell.setCellValue("狀態"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(6); headCell.setCellValue("生命週期"); headCell.setCellStyle(cellStyle); headCell = hssfRow.createCell(7); headCell.setCellValue("生成時間"); headCell.setCellStyle(cellStyle); // 新增資料內容 for (int i = 0; i < list.size(); i++) { hssfRow = sheet.createRow((int) i + 1); Sku student = list.get(i); // 建立單元格,並設定值 HSSFCell cell = hssfRow.createCell(0); cell.setCellValue(student.getSku()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(1); cell.setCellValue(student.getNwjduge()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(2); cell.setCellValue(student.getProname()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(3); cell.setCellValue(student.getSername()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(4); cell.setCellValue(student.getInvname()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(5); cell.setCellValue(student.getState()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(6); cell.setCellValue(student.getLife()); cell.setCellStyle(cellStyle); cell = hssfRow.createCell(7); cell.setCellValue(student.getCreatetime()); cell.setCellStyle(cellStyle); } // 儲存Excel檔案 try { OutputStream outputStream = new FileOutputStream("/usr/java/tomcat/apache-tomcat-7.0.85/temp/sku.xls"); workbook.write(outputStream); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
下載程式碼:
<% SkuDaoImpl sku = new SkuDaoImpl(); List<Sku> skuList = sku.findAll(); FullExcel.createExcel(skuList); //查詢的結果,便於插入Excel填充資料 response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); //使用者下載的儲存路徑 if (request.getParameter("file") != null) { OutputStream os = null; FileInputStream fis = null; try { String file = request.getParameter("file"); if (!(new File(file)).exists()) { System.out.println("沒有檔案"); return; } System.out.println("這個檔名為:"+file); os = response.getOutputStream(); response.setHeader("content-disposition", "attachment;filename=" + file); response.setContentType("application/vnd.ms-excel");//此項內容隨檔案型別而異 byte temp[] = new byte[1000]; fis = new FileInputStream(file); int n = 0; while ((n = fis.read(temp)) != -1) { os.write(temp, 0, n); } } catch (Exception e) { out.print("出錯"); } finally { if (os != null) os.close(); if (fis != null) fis.close(); } out.clear(); out = pageContext.pushBody(); } %> <form action="" method="post"> <select name="file"> <option value="/usr/java/tomcat/apache-tomcat-7.0.85/temp/sku.xls"> //從伺服器指定位置下載Excel檔案 服務SKU碼 </option> </select> <input type="submit" value="確定"> </form>
二、匯入
功能:匯入——選擇檔案——上傳,如下圖所示
實現過程:使用者先上傳檔案至伺服器的臨時位置,然後寫一個讀取excel的方法,程式從伺服器的臨時位置讀取excel檔案;然後迴圈工作表和行,將單元格的內容存入集合;再上傳至臨時表(每次先清空),再根據sku(主鍵)更新正式資料庫即可完成匯入檔案更新欄位資訊。
上傳程式碼,使用了fileupload的jar包:
<%
DiskFileItemFactory diskfactory = new DiskFileItemFactory();//建立工廠類物件
ServletFileUpload fileUpload = new ServletFileUpload(diskfactory);//使用工廠建立解析器物件
try {
List<FileItem> fileItems = fileUpload.parseRequest(request);
for(FileItem item:fileItems) {
if(item.isFormField()) {
System.out.println(new String(item.getString().getBytes("ISO-8859-1"),"utf-8"));
} else{
String fileName = item.getName();
item.write(new File("/usr/java/tomcat/apache-tomcat-7.0.85/temp/sku.xls"));//寫入到伺服器的臨時位置
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
List<Sku> temp=FullExcel.readExcel();//呼叫讀取Excel方法
FullExcel.truncate();//清空臨時表
for (Sku s : temp){
FullExcel.addTemp(s);//寫入臨時表
}
FullExcel.update();//更新正式表的欄位資訊
%>
Excel讀取程式碼:
public static List<Sku> readExcel() {
List<Sku> list = new ArrayList<Sku>();
HSSFWorkbook workbook = null;
try {
// 讀取Excel檔案
//String sep = System.getProperty("file.separator");
InputStream inputStream = new FileInputStream("/usr/java/tomcat/apache-tomcat-7.0.85/temp/sku.xls");
workbook = new HSSFWorkbook(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 迴圈工作表
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = workbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 迴圈行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow == null) {
continue;
}
// 將單元格中的內容存入集合
Sku sku = new Sku();
HSSFCell cell = hssfRow.getCell(0);
if (cell == null) {
continue;
}
sku.setSku(cell.getStringCellValue());
cell = hssfRow.getCell(1);
if (cell == null) {
continue;
}
sku.setNwjduge(cell.getStringCellValue());
cell = hssfRow.getCell(2);
if (cell == null) {
continue;
}
sku.setProname(cell.getStringCellValue());
cell = hssfRow.getCell(3);
if (cell == null) {
continue;
}
sku.setSername(cell.getStringCellValue());
cell = hssfRow.getCell(4);
if (cell == null) {
continue;
}
sku.setInvname(cell.getStringCellValue());
cell = hssfRow.getCell(5);
if (cell == null) {
continue;
}
sku.setState(cell.getStringCellValue());
cell = hssfRow.getCell(6);
if (cell == null) {
continue;
}
sku.setLife(cell.getStringCellValue());
list.add(sku);
}
}
return list;
}
//上傳新增(清空資料庫)
public static void truncate() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql1 = "truncate table TEMP";
try{
conn = DBUtil.getConnection();
ps = conn.prepareStatement(sql1);
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("新增資料失敗");
}
}
//上傳新增(寫入臨時資料庫)
public static void addTemp(Sku s) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql2="insert into TEMP(sku,nwjudge,proname,sername,invname,state,life)values(?,?,?,?,?,?,?)";
try{
conn = DBUtil.getConnection();
ps = conn.prepareStatement(sql2);
ps.setString(1, s.getSku());
ps.setString(2, s.getNwjduge());
ps.setString(3, s.getProname());
ps.setString(4, s.getSername());
ps.setString(5, s.getInvname());
ps.setString(6, s.getState());
ps.setString(7, s.getLife());
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("新增資料失敗");
}
}
//根據sku更新資料庫(正式資料庫)
public static void update() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql = "update SKU a,TEMP b set a.nwjudge=b.nwjudge,a.proname=b.proname,a.sername=b.sername,a.invname=b.invname,a.state=b.state,a.life=b.life WHERE a.sku=b.sku";
try{
conn = DBUtil.getConnection();
ps = conn.prepareStatement(sql);
ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
throw new SQLException("新增資料失敗");
}
}
}
剛開始做匯入匯出的時候還挺困難的,查閱了很多資料,這個算是比較簡單的匯入匯出了,其中用到了IO知識;其實可以直接從記憶體中讀取excel,我這邊做了一箇中轉的方法,先上傳至伺服器;至於更新用的臨時表,是為了程式效能,批量更新的時候如果資料量大,逐條更新會降低程式效能。此外主要就是利用了第三方包。不足之處還有很多,希望以後越做越好吧~