springmvc 的文件上传是基于commons-uploadfile的,因此要使用上传文件,需要引入包
pom.xml中加入:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
apache poi 是一个方便的插件,可对表格、word、ppt等进行操作,这次主要是表格测试,同样引入包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
自定义的Excel工具类,只有两个最基础的方法,读取表格数据,生成表格
NewExcelUtils.java:
package com.wyxh.bean;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
@Component
public class NewExcelUtils {
HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet
HSSFSheet s = wb.createSheet();
// declare a row object reference
HSSFRow r = null;
// declare a cell object reference
HSSFCell c = null;
public static void main(String[] args) throws IOException {
//new NewExcelUtils().getExcel();
}
/**
* 读取excel文件
*
* @throws IOException
* @throws IOException
*/
public String getExcel(String fileStyle,InputStream file) throws IOException, IOException {
Workbook getwb = null;
//实例化一个工作薄,传入的参数为要读取的excel文件,可以改为参数动态传入
//String file = "C:\\Users\\Administrator\\Documents\\WeChat Files\\Files\\test.xlsx";
//判断传入的文件是以 xls 还是 xlsx,湖区不同的Workbook实例
if(fileStyle.endsWith("xls")) {
getwb = new HSSFWorkbook(file);
}else if(fileStyle.endsWith("xlsx")) {
getwb = new XSSFWorkbook(file);
}
StringBuilder result = new StringBuilder();
//遍历当前工作薄中的所有sheet(工作表)
Iterator<Sheet> iterator = getwb.iterator();
while(iterator.hasNext()) {
//获取当前的工作表
Sheet next = iterator.next();
//获取工作表的一行,即:获取列名所在行
Row row = next.getRow(0);
//获取当前行的总列数
int cellnum = row.getPhysicalNumberOfCells();
//StringBuilder作为输出使用
StringBuilder str = new StringBuilder();
//遍历所有列
for(int i=0;i<cellnum;i++) {
//获取当前行每一列
Cell cell = row.getCell(i);
//获取当前列的值,追加到 StringBuilder 做输出用
str.append(cell.getStringCellValue());
str.append(" >> ");
}
result.append(str.toString());
System.out.println("列名:"+str.toString());
//以上部分是获取表中的第一行数据,即,每一列的名称
/*============================================================*/
//以下部分是获取每一行的数据,不包括第一行
//获取当前总行数
int rowNum = next.getLastRowNum();
//遍历所有行
for(int i = 1;i<rowNum;i++) {
//获取当前行
Row currentRow = next.getRow(i);
///获取当前行的 总列数
int cells = currentRow.getPhysicalNumberOfCells();
StringBuilder cellstr = new StringBuilder();
//遍历每一列
for(int cellNum = 0;cellNum<cells;cellNum++){
//获取当前行每一列
Cell cell = currentRow.getCell(cellNum);
//获取当前列的值,追加到 StringBuilder 做输出用
cellstr.append(cell.getStringCellValue());
cellstr.append(" >> ");
}
result.append(cellstr);
System.out.println(cellstr.toString());
}
}
return result.toString();
}
/*
* 输出excel文件
*/
public void setExcel() {
//设置表第一行的字段,即:列名
HSSFRow r = s.createRow(0);
//测试数据,这个地方可以换成参数动态传入
List<String> list =new ArrayList<String>();
list.add("id");
list.add("name");
list.add("work");
list.add("age");
list.add("size");
//根据传入的列名集合,设置列名
for(int i=0;i<list.size();i++) {
//设置列数
HSSFCell c = r.createCell(i);
//设置每一列的值
c.setCellValue(list.get(i));
}
//准备测试数据
ArrayList<String[]> strs = new ArrayList<String[]> ();
for(int i=0;i<10;i++) {
String[] str = new String[] {i+"","haha"+i,"修仙"+i,"000"+i,i+15+""};
strs.add(str);
}
//设置数据
//遍历数据
for(int i =0;i<strs.size();i++) {
//根据数据大小,设置行数
HSSFRow rr = s.createRow(i+1);
for(int csize=0;csize<strs.get(0).length;csize++) {
//设置列数
HSSFCell c = rr.createCell(csize);
//设置每一列的值
c.setCellValue(strs.get(i)[csize]);
}
}
//输出为文件/保存文件
FileOutputStream out = null;
try {
out = new FileOutputStream("test.xls");
wb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Controller层的 IndexController.java
package com.wyxh.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.wyxh.bean.ExcelUtils;
import com.wyxh.bean.NewExcelUtils;
@RestController
public class IndexController {
/**
* 自定义工具类
*/
@Autowired
private NewExcelUtils newExcelUtils;
/**
* 用于下载文件的方法
* @return 使用spring中的 ResponseEntity<byte[]> 返回以字节数组包装的文件,用于浏览器端下载
* @throws Exception
*/
@RequestMapping(value="/download.do",method=RequestMethod.GET)
public ResponseEntity<byte[]> download() throws Exception{
String path = "C:\\Users\\Administrator\\Documents\\WeChat Files\\Files\\test.xls";
File file = new File(path);
InputStream in = new FileInputStream(file);
byte[] bytes = new byte[in.available()];
in.read(bytes);
//这里的HttpHeaders为org.springframework.http.HttpHeaders中的,!!!注意不是javax包下的
HttpHeaders httpHerders = new HttpHeaders();
//设置响应头信息,告知浏览器下载该文件
httpHerders.add("Content-Disposition", "attachment;fileName=" + file.getName());
//设置响应头为 200(OK)
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(bytes,httpHerders,status);
return result;
}
/**
* 用于上传表格文件的方法可上传 .xls/.xlsx 两种格式的表格文件
* @param file 上传的文件 使用spring的 MultipartFile
* @return 这里将上传的表格中的数据,读取、转成字符串返回
*/
@RequestMapping(value="/upexcel.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public String upExcel(@RequestParam("file") MultipartFile file) {
String filename = file.getOriginalFilename();
String substring = filename.substring(filename.lastIndexOf("."));
System.out.println("截取的文件名:"+substring);
try {
//自定义的excel文件上传类,传入的参数为:文件名的后缀符(用于判断是xls文件还是xlsx文件),上传文件的InputStream
//这里的返回值是,上传表格中的数据转为string
return newExcelUtils.getExcel(substring,file.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
return "上传出错…";
}
}
/**
* 用于上传文件的方法
* @param request
* @param filename
* @param file
* @return
*/
@RequestMapping(value="/upload.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
public String findById(HttpServletRequest request,@RequestParam("file") MultipartFile file) {
//获取文件原始名
String originalFilename = file.getOriginalFilename();
//获取要保存的目标文件夹路径
String path = request.getServletContext().getRealPath("/upload/");
System.out.println("path====="+path);
File upfile = new File(path,originalFilename);
//判断当前文件是否存在,不存在则创建
if(!upfile.getParentFile().exists()) {
upfile.getParentFile().mkdirs();
}
try {
//保存文件到目标地址
file.transferTo(new File(path+File.separator+originalFilename));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
return "上传失败,参数错误";
} catch (IOException e) {
// TODO Auto-generated catch block
return "上传失败,IO异常";
}
return "上传成功";
}
}
文件上传下载,以及表格操作的核心代码就以上两个,其他的代码已省略