這篇文章給大家介紹利用Java怎么上傳與下載Excel表格,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
Excel表格文件的上傳和下載,java中涉及到文件肯定會有io流的知識。
而excel文件就要涉及到poi技術,而excel的版本包括:2003-2007和2010兩個版本, 即excel的后綴名為:xls和xlsx。
這里我是按照正規的項目流程做的案例,所以可能會比網上的一些Demo復雜一些。不過文件的上傳和下載基本都是一套固定的流程,只是每個人的實現方式不太相同。
數據庫我用的是MySql。
下面是我的項目目錄:

按照正常的項目做了分層處理,文件上傳的業務我放到了service處理,而文件下載業務還在controller層。
對前端請求處理,我分成了兩個方法都放在HandleExcelController里面,這個類繼承了BaseExcelController,基本的文件操作處理在BaseExcelController里面。
BaseExcelController繼承了BaseController,BaseController類是所有controller的父類,這里用到的不太多,這個類封裝了response返回值等的處理等一些方法。
項目中除了springMVC和mybatis的jar包之外還引入了:

上傳和下載excel文件:
1、創建需要上傳的excel文件,為了簡化,我這里只寫了四列,即四個字段

2、創建jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Excel文件處理</title>
<script type="text/javascript" src="<c:url value='/res/js/jquery.js'/>"></script>
<script>
$(function(){
var $wrap = $(".wrap");
var find = function(str){
return $wrap.find(str);
}
var getJname = function(name){
return find("input[name='"+name+"']");
}
getJname("Upload").click(function(){
var form = new FormData(document.getElementById("tf"));
$.ajax({
url:"<c:url value='/File/UploadExcel'/>",
type:"post",
data:form,
dataType:"json",
processData:false,
contentType:false,
success:function(data){
//window.clearInterval(timer);
if(data.success == "success"){
alert("提交文件成功,已將數據存入數據庫");
}
},
error:function(e){
alert("錯誤!");
//window.clearInterval(timer);
}
});
})
getJname("Download").click(function(){
$.post("<c:url value='/File/DownLoadExcel'/>",{"id":"3"},function(data){
//alert("下載文件成功");
},"json")
})
})
</script>
</head>
<body>
<div class="wrap">
<form id="tf">
<p>
<input type="file" name="file" value="選擇文件"/>
Excel文件上傳:<input type="button" name="Upload" value="upload"/>
</p>
<p>
Excel文件下載:<input type="button" name="Download" value="updown"/>
</p>
</form>
</div>
</body>
</html>3、依次創建controller、service、domain、mapper層,注意它們的依賴關系
1)、controller層的處理,在HandleExcelController里面注入BaseExcelService。因為只是做個示范,所欲我這里將泛型固定為Students類
BaseExcelController代碼:
package cn.wangze.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import cn.wangze.domain.Students;
public class BaseExcelController extends BaseController{
//獲取文件的路徑
String separator = System.getProperty("file.separator");
//驗證元素是否為空
@SuppressWarnings("all")
public boolean isEmpty(Object obj){
if(obj instanceof Object[]){
if(((Object[]) obj).length==0){
return true;
}
if(obj == null) return true;
if((String.valueOf(obj).trim()).length() == 0){
return true;
}
if(obj instanceof List){
if(((List) obj) == null || ((List)obj).size() == 0){
return true;
}
}
}
return false;
}
/**
* 文件上傳部分
* */
//驗證文件
protected boolean checkPathName(String fileName,HttpServletResponse response){
//驗證文件是否存在
if(isEmpty(fileName)){
sendError("上傳文件不存在",response);
return false;
}
//驗證文件是否是以xls或者xlsx做后綴的文件,如果不是就返回錯誤信息
if(!(StringUtils.endsWithIgnoreCase(fileName,".xls")||StringUtils.endsWithIgnoreCase(fileName, ".xlsx"))){
sendError("上傳文件類型錯誤,請核對后重新上傳?",response);
}
return true;
}
//獲取文件的sheet
protected Sheet getSheet(MultipartFile file,String path,String fileName) throws IllegalStateException, IOException{
//找到要存放到項目里面的路徑,新建文件
File targetFile = new File(path, fileName);
targetFile.mkdirs();
if (targetFile.exists()) {
targetFile.delete();
file.transferTo(targetFile);
} else {
file.transferTo(targetFile);
}
//封裝輸入流,封裝sheet里面的內容
InputStream is = null;
try{
is = new FileInputStream(path+separator+fileName);
//判斷版本是否為Excel加強版
if(StringUtils.endsWithIgnoreCase(fileName, ".xls")){
return new HSSFWorkbook(is).getSheetAt(0);
}else if(StringUtils.endsWithIgnoreCase(fileName, ".xlsx")){
return new XSSFWorkbook(is).getSheetAt(0);
}
return null;
}
finally{
if(is != null){
is.close();
}
}
}
/**
* 文件下載部分
* */
//根據傳入的Sting值,判斷生成在excel表的位置
private HSSFCellStyle getPublicStyle(HSSFWorkbook workbook,String key){
HSSFFont font = workbook.createFont();
HSSFCellStyle style = workbook.createCellStyle();
HSSFPalette customPalette = workbook.getCustomPalette();
customPalette.setColorAtIndex(HSSFColor.TEAL.index, (byte) 64, (byte) 148, (byte) 160);
customPalette.setColorAtIndex(HSSFColor.ORANGE.index, (byte) 170, (byte) 204, (byte) 204);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
if(key=="head"){
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
font.setFontHeightInPoints((short)12);
font.setColor(HSSFColor.TEAL.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
}
if(key=="title"){
font.setColor(HSSFColor.WHITE.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.WHITE.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.WHITE.index);
style.setFont(font);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.ORANGE.index);
style.setFillBackgroundColor(HSSFColor.ORANGE.index);
}
return style;
}
//創建head頭信息
private void createHead(HSSFSheet sheet,HSSFCellStyle style,String[] title){
HSSFRow row1 = sheet.createRow(0);
HSSFCell cellTitle = row1.createCell(0);
cellTitle.setCellValue(new HSSFRichTextString(title[0]));
sheet.addMergedRegion(new CellRangeAddress(0,0,0,title.length-2));
cellTitle.setCellStyle(style);
}
//創建title信息
private void createTitle(HSSFSheet sheet,HSSFCellStyle style,String[] label,int columnNum){
HSSFRow row2 = sheet.createRow(1);
HSSFCell cell1 = null;
for(int n=0;n<columnNum;n++){
cell1 = row2.createCell(n);
cell1.setCellValue(label[n+1]);
cell1.setCellStyle(style);
}
}
//創建content數據信息
private void createContent(HSSFSheet sheet,HSSFCellStyle style,Collection<Students> list,int columnNum,String[] parameters){
int index= 0;
Iterator<Students> it = list.iterator();
while(it.hasNext()){
index++;
Students cash = it.next();
int num2 = parameters.length;
HSSFRow row = sheet.createRow(index+1);
initCells(style, num2,cash, parameters,row);
}
}
//驗證是否為中文
public boolean checkChinese(String s){
int n=0;
boolean flag =false;
for(int i=0; i<s.length(); i++) {
n = (int)s.charAt(i);
flag=(19968 <= n && n <40623)?true:false;
}
return flag;
}
//將數據設置到excel表格內
public void initCells(HSSFCellStyle style, int columnNum, Students t,
String[] endContent, HSSFRow row3) {
for(int j=0;j<columnNum;j++){
HSSFCell cell = row3.createCell(j);
String fieldName = endContent[j];
try{
if(fieldName!="" && !checkChinese(fieldName)){
String getMethodName = "get" +fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
Class clazz = t.getClass();
Method getMethod = clazz.getMethod(getMethodName, new Class[]{});
String value = (String)getMethod.invoke(t, new Object[]{});
cell.setCellValue(value);
}else{
cell.setCellValue(fieldName);
}
cell.setCellStyle(style);
}catch(Exception e){
e.printStackTrace();
}
}
}
public void createEnd(HSSFSheet sheet,HSSFCellStyle style,int numText,int columnNum,Students t,String[] endContent){
HSSFRow row3 = sheet.createRow(numText+2);
initCells(style, columnNum, t, endContent, row3);
}
//根據service查詢到的數據,創建excel表并插入查詢的數據信息
protected String getOutputName(List<Students> list, String path, String[] title, String[] parameters, Students t, String[] endContent)
throws IOException{
//根據傳入的title數組的第一個值,設置文件名稱
String filename = title[0]+"_"+ new SimpleDateFormat("yyyyMMdd").format(new Date())+".xls";
//輸出流放到文件的本地位置
FileOutputStream fos = new FileOutputStream(path+separator+filename);
//列數,根據title的個數,除去第一個就是每列title的信息
int columnNum = title.length-1;
int numText = list.size();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
sheet.setDefaultColumnWidth (20);
sheet.setDefaultRowHeight((short)400);
HSSFCellStyle contentStyle = this.getPublicStyle(workbook,"");
HSSFCellStyle titleStyle = this.getPublicStyle(workbook,"title");
HSSFCellStyle headerStyle = this.getPublicStyle(workbook,"head");
createHead(sheet,headerStyle,title);
createTitle(sheet,titleStyle,title,columnNum);
createContent(sheet,contentStyle,list,columnNum,parameters);
//createEnd(sheet,contentStyle,numText,columnNum,t,endContent);
workbook.write(fos);
fos.flush();
fos.close();
return filename;
}
}HandleExcelController用來處理前端請求,代碼如下:
package cn.wangze.controller;
import java.io.File;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import cn.wangze.domain.Students;
import cn.wangze.service.BaseExcelService;
@Controller
@RequestMapping("/File")
public class HandleExcelController extends BaseExcelController{
@Autowired
private BaseExcelService baseExcelService;
@RequestMapping("/UploadExcel")
public void UploadExcel(MultipartFile file,HttpSession session,HttpServletResponse response) throws Exception{
//如果上傳的文件不存在,拋出異常
if(file == null){
throw new Exception("文件不存在");
}
//獲取文件名
String fileName = file.getOriginalFilename();
//選擇上傳的文件存放到項目的路徑
String path = session.getServletContext().getRealPath(separator+"res"+separator+"upload");
if(!checkPathName(fileName,response)) return ;
String msg = baseExcelService.loadExcel(getSheet(file, path, fileName));
sendMsg(true,msg,response);
}
@RequestMapping("/DownLoadExcel")
public void UpdownExcel(Students student,HttpServletResponse res,HttpSession session,HttpServletResponse response)
throws Exception{
List<Students> stus = baseExcelService.queryList(student);
if(stus.size()==0){
res.sendRedirect("/index.jsp");
return;
}
//下載的excel文件存放的本地路徑
String path = session.getServletContext().getRealPath(separator+"res"+separator+"exportExcel"+separator);
ServletOutputStream os = res.getOutputStream();
Students t = baseExcelService.queryTotal(student);
//標題文字,數值中的第一個值+當前日期為文件名稱,以后的每個元素為每列的標題
String[] title={"studets04","id","名字","年齡","性別"};//標題文字
//對應實體類的屬性值
String[] parameters ={"id","name","age","sex"};
String[] endContent = {"","","",""};
//調用父類的處理方法,生成excel文件
String filename = getOutputName(stus,path,title,parameters,t,endContent);
try {
res.reset();
res.setCharacterEncoding("utf8");
res.setContentType("application/vnd.ms-excel;charset=utf8");
res.setHeader("Content-Disposition", "attachment;fileName="
+new String(filename.getBytes("utf-8"),"iso-8859-1"));
os.write(FileUtils.readFileToByteArray(new File(path+separator+filename)));
sendResult(true,response);
os.flush();
} finally {
if (os != null) {
os.close();
}
}
}
}2)、service層的處理,把StudentsMapper注入到BaseExcelService
BaseExcelService代碼:
package cn.wangze.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wangze.domain.Students;
import cn.wangze.mapper.StudentsMapper;
@Service
public class BaseExcelService {
@Autowired
private StudentsMapper<Students> studentsMapper;
//判斷字符串是否為空
public boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
//獲取單個表格(字段)存放的信息
private String getValue(Cell cell,String cellLable,Map<String,String> errMap){
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue().trim();
return value;
}
//通過這個方法將excel表的每行的數據放到info對象里面
private String addInfo(Row row,Students info){
Map<String,String> errMap = new HashMap<String,String>();
String id = getValue(row.getCell(0),"ID",errMap);
String username = getValue(row.getCell(1),"姓名",errMap);
String age = getValue(row.getCell(2),"年齡",errMap);
String sex = getValue(row.getCell(3),"性別",errMap);
String errMsg = errMap.get("errMsg");
if(!isEmpty(errMsg)){
return errMsg;
}
info.setId(id);
info.setName(username);
info.setAge(age);
info.setSex(sex);
return null;
}
public String loadExcel(Sheet sheet) throws Exception{
//新建一個List集合,用來存放所有行信息,即每行為單條實體信息
List<Students> infos = new ArrayList<Students>();
//獲取到數據行數,第一行是title,不需要存入數據庫,所以rowNum從1開始
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Students info = new Students();
String errMsg2 = addInfo(sheet.getRow(rowNum),info);
if(errMsg2 != null) return errMsg2;
infos.add(info);
}
if(infos.isEmpty()){
return "沒有解析到學生數據,請查驗EXCEL文件";
}
//通過studentsMapper的insertSheetData方法,將實體類存放的數據插入到數據庫
int result = studentsMapper.insertSheetData(infos);
//若插入成功會返回大于1的整數,返回success
if(result >= 1){
return "success";
}
return "error";
}
//查詢所有數據庫存放的學生信息
public List<Students> queryList(Students students){
return studentsMapper.queryList(students);
}
//獲取到的學生實體信息
public Students queryTotal(Students students){
return studentsMapper.queryTotal(students);
}
public void downExcel(HttpSession session,String separator){
}
}3)、實體層的處理,字段要對應excel表的字段
package cn.wangze.domain;
public class Students {
String id;
String name;
String age;
String sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}4)、dao層處理:StudentsMapper.java是一個接口,業務到數據庫需要執行的方法在這里聲明,StudentsMapper.xml相當于接口的實現類,用來連接java和數據庫的操作。
StudentsMapper.java代碼:
package cn.wangze.mapper;
import java.util.List;
public interface StudentsMapper<T> {
public int insertSheetData(List<T> list);
public List<T> queryList(T t);
public T queryTotal(T t);
}StudentsMapper.xml代碼:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wangze.mapper.StudentsMapper">
<sql id="ColumnList">
id,name,age,sex
</sql>
<sql id="ColumnList_t" >
t.id,t.name,t.age,t.sex
</sql>
<sql id="ValueList">
#{id},#{name},#{age},#{sex}
</sql>
<sql id="WhereClause">
where 1=1
<if test="id!=null and id!=''">and id=#{id}</if>
<if test="name!=null and name!=''">and name=#{name}</if>
<if test="age!=null and age!=''">and age=#{age}</if>
<if test="sex!=null and sex!=''">and sex=#{sex}</if>
</sql>
<sql id="WhereClause_pager" >
where 1=1
<if test="t.id!=null and t.id!=''">and id=#{t.id}</if>
<if test="t.name!=null and t.name!=''">and name=#{t.name}</if>
<if test="t.age!=null">and age=#{t.age}</if>
<if test="t.sex!=null and t.sex!=''">and sex=#{t.sex}</if>
</sql>
<sql id="SetClause" >
set
<trim suffixOverrides="," >
<if test="id!=null">id=#{id},</if>
<if test="name!=null">name=#{name},</if>
<if test="pid!=null">age=#{age},</if>
<if test="url!=null">sex=#{sex},</if>
</trim>
</sql>
<select id="queryList" resultType="Students">
select <include refid="ColumnList"/> from students
</select>
<select id="queryTotal" parameterType="Students" resultType="Students">
select <include refid="ColumnList" /> from students <include refid="WhereClause"/>
<!-- (select <include refid="ColumnList"/> from t_account_cash t
<include refid="WhereClauseQuery"/> group by to_char(t.add_time,'yyyy-mm-dd'),t.account_id) a -->
</select>
<insert id="insertSheetData" useGeneratedKeys="true" parameterType="java.util.List">
<!-- <selectKey resultType="long" keyProperty="id" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey> -->
insert into students (id,name,age,sex)
values
<foreach collection="list" item="item" index="index" separator="," >
(#{item.id},#{item.name},#{item.age},#{item.sex})
</foreach>
</insert>
</mapper>所有的代碼就是這些了,操作的時候需要注意的多是路徑的問題。最復雜的就是BaseExcelController的操作,它做的事情就是解析上傳和創建下載excel文件。
執行完之后的結果圖是這樣:
在數據庫查看上傳的excel表:

下載到D:\tomcat\tomcat6.0.32\webapps\ExcelHandleDemo\res\exportExcel文件夾下的excel表:

這里有一點不足的地方,我相信你已經發現了,就是下載完excel表格之后,前端還沒有和業務對接上,沒有相應的提示來告訴操作人執行結果,只能通過代碼設置好的路徑去查看文件夾下是否有下載的excel文件,
關于利用Java怎么上傳與下載Excel表格就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。