poi+springmvc+springjdbc 가 져 오기 엑셀 인 스 턴 스 내 보 내기
쓸데없는 말 은 그만 하고,
1.필요 한 jar 패키지:
2.전단 코드:
ieport.jsp:
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=utf-" pageEncoding="utf-"%>
<!DOCTYPE html PUBLIC "-//WC//DTD XHTML . Transitional//EN" "http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd">
<html xmlns="http://www.w.org//xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-" />
<title> \ </title>
<script type="text/javascript">
function exportFile(){
window.location.href = "<%=request.getContextPath()%>/export.go";
}
</script>
</head>
<body>
<form action="import.go" method="post" enctype="multipart/form-data">
:<input type="file" name="uploadFile"/>
<br></br>
<input type="submit" value=" "/>
<input type="button" value=" " onclick="exportFile()"/>
</form>
</body>
</html>
success.jsp:
<%@ page language="java" contentType="text/html; charset=utf-" pageEncoding="utf-"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//WC//DTD XHTML . Transitional//EN" "http://www.w.org/TR/xhtml/DTD/xhtml-transitional.dtd">
<html xmlns="http://www.w.org//xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-" />
<title> </title>
<script type="text/javascript">
// var secUserList = '${secUserList}';
// alert(secUserList);
</script>
</head>
<body>
<c:if test="${type == 'import'}">
<div> !</div>
<c:forEach items="${secUserList}" var="secUser">
<div>Id:${secUser.userId} | Name:${secUser.userName} | Password:${secUser.userPassword}</div>
</c:forEach>
</c:if>
<c:if test="${type == 'export'}">
<div> !</div>
</c:if>
</body>
</html>
3.배경 코드:controller:
package com.controller;
import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.domain.SecUser;
import com.service.IEportService;
@Controller
public class IEportController {
@Resource
private IEportService ieportService;
@RequestMapping("/import")
public ModelAndView importFile(@RequestParam(value="uploadFile")MultipartFile mFile, HttpServletRequest request, HttpServletResponse response){
String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
List<SecUser> secUserList = ieportService.importFile(mFile, rootPath);
ModelAndView mv = new ModelAndView();
mv.addObject("type", "import");
mv.addObject("secUserList", secUserList);
mv.setViewName("/success");
return mv;
}
@RequestMapping("/export")
public ModelAndView exportFile(HttpServletResponse response) {
ieportService.exportFile(response);
ModelAndView mv = new ModelAndView();
mv.addObject("type", "export");
mv.setViewName("/success");
return mv;
}
}
service:
package com.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.dao.IEportDao;
import com.domain.SecUser;
@Service
public class IEportService {
@Resource
private IEportDao ieportDao;
public List<SecUser> importFile(MultipartFile mFile, String rootPath){
List<SecUser> secUserList = new ArrayList<SecUser>();
String fileName = mFile.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + , fileName.length());
String ym = new SimpleDateFormat("yyyy-MM").format(new Date());
String filePath = "uploadFile/" + ym + fileName;
try {
File file = new File(rootPath + filePath);
if (file.exists()) {
file.delete();
file.mkdirs();
}else {
file.mkdirs();
}
mFile.transferTo(file);
if ("xls".equals(suffix) || "XLS".equals(suffix)) {
secUserList = importXls(file);
ieportDao.importFile(secUserList);
}else if ("xlsx".equals(suffix) || "XLSX".equals(suffix)) {
secUserList = importXlsx(file);
ieportDao.importFile(secUserList);
}
} catch (Exception e) {
e.printStackTrace();
}
return secUserList;
}
private List<SecUser> importXls(File file) {
List<SecUser> secUserList = new ArrayList<SecUser>();
InputStream is = null;
HSSFWorkbook hWorkbook = null;
try {
is = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(is);
HSSFSheet hSheet = hWorkbook.getSheetAt();
if (null != hSheet){
for (int i = ; i < hSheet.getPhysicalNumberOfRows(); i++){
SecUser su = new SecUser();
HSSFRow hRow = hSheet.getRow(i);
su.setUserName(hRow.getCell().toString());
su.setUserPassword(hRow.getCell().toString());
secUserList.add(su);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (null != is) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != hWorkbook) {
try {
hWorkbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return secUserList;
}
private List<SecUser> importXlsx(File file) {
List<SecUser> secUserList = new ArrayList<SecUser>();
InputStream is = null;
XSSFWorkbook xWorkbook = null;
try {
is = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(is);
XSSFSheet xSheet = xWorkbook.getSheetAt();
if (null != xSheet) {
for (int i = ; i < xSheet.getPhysicalNumberOfRows(); i++) {
SecUser su = new SecUser();
XSSFRow xRow = xSheet.getRow(i);
su.setUserName(xRow.getCell().toString());
su.setUserPassword(xRow.getCell().toString());
secUserList.add(su);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (null != is) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != xWorkbook) {
try {
xWorkbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return secUserList;
}
public void exportFile(HttpServletResponse response) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
OutputStream os = null;
XSSFWorkbook xWorkbook = null;
try {
String fileName = "User" + df.format(new Date()) + ".xlsx";
os = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename = " + URLEncoder.encode(fileName, "UTF-"));
response.setContentType("application/octet-streem");
xWorkbook = new XSSFWorkbook();
XSSFSheet xSheet = xWorkbook.createSheet("UserList");
//set Sheet
setSheetHeader(xWorkbook, xSheet);
//set Sheet
setSheetContent(xWorkbook, xSheet);
xWorkbook.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != os) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != xWorkbook) {
try {
xWorkbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* set Sheet
* @param xWorkbook
* @param xSheet
*/
private void setSheetHeader(XSSFWorkbook xWorkbook, XSSFSheet xSheet) {
xSheet.setColumnWidth(, * );
xSheet.setColumnWidth(, * );
xSheet.setColumnWidth(, * );
CellStyle cs = xWorkbook.createCellStyle();
//
cs.setAlignment(CellStyle.ALIGN_CENTER);
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
//
Font headerFont = xWorkbook.createFont();
headerFont.setFontHeightInPoints((short) );
headerFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontName(" ");
cs.setFont(headerFont);
cs.setWrapText(true);//
XSSFRow xRow = xSheet.createRow();
XSSFCell xCell = xRow.createCell();
xCell.setCellStyle(cs);
xCell.setCellValue(" ID");
XSSFCell xCell = xRow.createCell();
xCell.setCellStyle(cs);
xCell.setCellValue(" ");
XSSFCell xCell = xRow.createCell();
xCell.setCellStyle(cs);
xCell.setCellValue(" ");
}
/**
* set Sheet
* @param xWorkbook
* @param xSheet
*/
private void setSheetContent(XSSFWorkbook xWorkbook, XSSFSheet xSheet) {
List<SecUser> secUserList = ieportDao.getSecUserList();
CellStyle cs = xWorkbook.createCellStyle();
cs.setWrapText(true);
if (null != secUserList && secUserList.size() > ) {
for (int i = ; i < secUserList.size(); i++) {
XSSFRow xRow = xSheet.createRow(i + );
SecUser secUser = secUserList.get(i);
for (int j = ; j < ; j++) {
XSSFCell xCell = xRow.createCell(j);
xCell.setCellStyle(cs);
switch (j) {
case :
xCell.setCellValue(secUser.getUserId());
break;
case :
xCell.setCellValue(secUser.getUserName());
break;
case :
xCell.setCellValue(secUser.getUserPassword());
break;
default:
break;
}
}
}
}
}
}
dao:
package com.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.domain.SecUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
@Repository
public class IEportDao {
@Resource
private JdbcTemplate jdbcTemplate;
private RowMapper<SecUser> suRowMapper = null;
private IEportDao() {
suRowMapper = new RowMapper<SecUser>() {
@Override
public SecUser mapRow(ResultSet rs, int index) throws SQLException {
SecUser secUser = new SecUser();
secUser.setUserId(rs.getString("USER_ID"));
secUser.setUserName(rs.getString("USER_NAME"));
secUser.setUserPassword(rs.getString("USER_PASSWORD"));
return secUser;
}
};
}
public void importFile(List<SecUser> secUserList) {
try {
String sql = "INSERT INTO SEC_USER VALUES(UUID(),?,?)";
List<Object[]> paramsList = new ArrayList<Object[]>();
for (int i = ; i < secUserList.size(); i++) {
SecUser secUser = secUserList.get(i);
Object[] params = new Object[]{secUser.getUserName(),secUser.getUserPassword()};
paramsList.add(params);
}
jdbcTemplate.batchUpdate(sql, paramsList);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<SecUser> getSecUserList() {
List<SecUser> suList = new ArrayList<SecUser>();
StringBuffer sb = new StringBuffer();
sb.append("SELECT SU.USER_ID,SU.USER_NAME,SU.USER_PASSWORD FROM SEC_USER SU");
try {
suList = jdbcTemplate.query(sb.toString(), suRowMapper);
} catch (Exception e) {
e.printStackTrace();
}
return suList;
}
}
domain:
package com.domain;
public class SecUser {
String userId; // ID
String userName; //
String userPassword; //
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
4.프로필:
<?xml version="." encoding="UTF-"?>
<web-app xmlns:xsi="http://www.w.org//XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app__.xsd"
id="WebApp_ID" version=".">
<display-name>SpringSpringmvcPoi</display-name>
<welcome-file-list>
<welcome-file>ieport.jsp</welcome-file>
</welcome-file-list>
<!-- Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:application-context.xml
classpath:dataSource-context.xml
</param-value>
</context-param>
<!-- Spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- SpringMVC DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- SpringMVC -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.go</url-pattern>
</servlet-mapping>
<!-- , -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<?xml version="." encoding="UTF-"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w.org//XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-..xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd">
<!-- -->
<context:component-scan base-package="com.controller"></context:component-scan>
<!-- SpringMVC -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
<?xml version="." encoding="UTF-"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w.org//XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd">
<context:component-scan base-package="com"></context:component-scan>
</beans>
<?xml version="." encoding="UTF-"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w.org//XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- jdbc -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- -->
<bean id="dataSource" class="com.mchange.v.cp.ComboPooledDataSource" destroy-method="close">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<!-- ,CP -->
<property name="acquireIncrement" value=""></property>
<!-- , minPoolSize maxPoolSize -->
<property name="initialPoolSize" value=""></property>
<property name="maxPoolSize" value=""></property>
<property name="minPoolSize" value=""></property>
<property name="maxConnectionAge" value=""></property>
<property name="maxIdleTime" value=""></property>
<property name="maxIdleTimeExcessConnections" value=""></property>
<property name="breakAfterAcquireFailure" value="false"></property>
<property name="testConnectionOnCheckout" value="false"></property>
<property name="testConnectionOnCheckin" value="false"></property>
<!-- -->
<property name="idleConnectionTestPeriod" value=""></property>
<property name="acquireRetryAttempts" value=""></property>
<property name="acquireRetryDelay" value=""></property>
<property name="preferredTestQuery" value="SELECT FROM DUAL"></property>
</bean>
<!-- Jdbc JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
</beans>
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:/mydb
jdbc.user=myuser
jdbc.password=myuser
5.디 렉 터 리 구조:6.결과 시연
가 져 오기:
내 보 내기:
PS:
1.본 x 초보 자 는 첨부 파일 을 어떻게 추가 하 는 지 아직 잘 모 르 기 때문에 모든 코드 를 붙 이 고 디 렉 터 리 구 조 를 추가 합 니 다.나중에 첨부 파일 을 어떻게 추가 하 는 지 알 고 수정 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.