废话不多说,直接上代码:这个是对Excel文件的上传数据库、下载处理代码。
@Resource
private SQLFileDao SQLFiledao;
//文件上传service
@Override
public boolean doSQLfileUpload(HttpServletRequest request,MultipartFile file) {
// TODO Auto-generated method stub
//文件方式上传
/* String fileName = file.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("/uploadSQLfile/") + fileName;
File dest = new File(path);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest); //保存文件
return true;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
Workbook wb = null;
InputStream is=null;
try {
is = file.getInputStream();
wb = new XSSFWorkbook(is);
/* String uploadfileName=file.getOriginalFilename();
if(!uploadfileName.matches("^.+\\.(?i)(xls)$")) {
wb = new HSSFWorkbook(is);
}
if (uploadfileName.matches("^.+\\.(?i)(xlsx)$")) {
wb = new XSSFWorkbook(is);
}*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Sheet sheet = wb.getSheetAt(0);
List<SQLFileBean> sqlFileList = new ArrayList<SQLFileBean>();
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
row.getCell(1).setCellType(CellType.STRING);
row.getCell(2).setCellType(CellType.STRING);
SQLFileBean sqlFileBean = new SQLFileBean();
// String id = row.getCell(0).getStringCellValue();
String username = row.getCell(1).getStringCellValue();
String userpassword = row.getCell(2).getStringCellValue();
//sqlFileBean.setId(Integer.parseInt(id));
sqlFileBean.setUserName(username);
sqlFileBean.setUserPassword(userpassword);
sqlFileList.add(sqlFileBean);
}
for (SQLFileBean sqlFileBean : sqlFileList) {
SQLFiledao.doSQLfileUpload(sqlFileBean);
}
return true;
}
//文件下载service
@Override
public List<SQLFileBean> doSQLfiledownload(HttpServletResponse response) {
// TODO Auto-generated method stub
//生成一个工作簿
XSSFWorkbook workbook=new XSSFWorkbook();
//生成一个表格
XSSFSheet sheet=workbook.createSheet(fileName);
//设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short)20);
//产生表格标题行
XSSFRow row=sheet.createRow(0);
for(short i=0;i<headers.length;i++) {
XSSFCell cell=row.createCell(i);
XSSFRichTextString richTextString=new XSSFRichTextString(headers[i]);
cell.setCellValue(richTextString);
}
BufferedOutputStream fos = null;
//遍历数据集合,产生数据行
try {
Iterator<SQLFileBean> it=SQLFiledao.doGetSQLFileList().iterator();
int index=0;
while(it.hasNext()) {
index++;
row=sheet.createRow(index);
SQLFileBean t=it.next();
//利用反射,根据javabean属性的先后顺序,动态调用getxx()方法得到属性值
Field[] fields=t.getClass().getDeclaredFields();
for (int i = 0; i < headers.length; i++) {
XSSFCell cell=row.createCell(i);
Field field=fields[i];
String fielName=field.getName();
String getMethodName="get"+fielName.substring(0, 1).toUpperCase()+fielName.substring(1);
Class tcls=t.getClass();
Method getMethod=tcls.getMethod(getMethodName, new Class[]{});
Object value=getMethod.invoke(t, new Object[]{});
//判断值得类型后进行强制类型转换
String textValue=null;
//其他数值类型当做字符串简单处理
if(value!=null&&value!=""){
textValue=value.toString();
}
if(textValue!=null) {
XSSFRichTextString richTextString=new XSSFRichTextString(textValue);
cell.setCellValue(richTextString);
}
}
}
String XfileName=fileName+".xlsx";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + new String (XfileName.getBytes("gb2312"),"ISO8859-1"));
fos=new BufferedOutputStream(response.getOutputStream());
workbook.write(fos);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
接下来展示简单的基础文件处理,上传文件到服务器路径和下载:
/**
* 实现文件上传
* */
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam MultipartFile fileName,Model model,HttpServletRequest request){
/*boolean flag=fileServiceImp.fileUpload(fileName);
if(flag){
model.addAttribute("message", "上传成功");
return "department/departmentlist";
}
model.addAttribute("message", "上传失败");
return "department/departmentlist";*/
model.addAttribute("message", "上传失败");
if(fileName.isEmpty()){
return "uploadFile/uploadFilelist";
}
String pathfileName = fileName.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("/temp/") + pathfileName;
File dest = new File(path);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdirs();
}
try {
fileName.transferTo(dest); //保存文件
selectTextFile(model,request);
System.out.println("fileName:"+fileName);
model.addAttribute("message", "上传成功");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "uploadFile/uploadFilelist";
}
/**
* 实现文件查询
* @throws IOException
* @throws FileNotFoundException
* */
@RequestMapping("/selectTextFile")
public String selectTextFile(Model model, HttpServletRequest request) throws FileNotFoundException, IOException{
String path = request.getSession().getServletContext().getRealPath("/temp");
// String path = ServletActionContext.getServletContext().getRealPath("/");
// 获得指定文件对象
System.out.println("path:"+path);
File file = new File(path);
// 获得该文件夹内的所有文件
if (file.exists() && file.isDirectory()) {
File[] array = file.listFiles();
if (array != null) {
ArrayList<FileBean> fileList=new ArrayList<FileBean>();
for(int i=0;i<array.length;i++)
{
FileBean filebean=new FileBean();
if(array[i].isFile())//如果是文件
{
// 只输出文件名字
filebean.setFileName(array[i].getName());
// 输出当前文件的完整路径
filebean.setFilePath(array[i].getPath());
// 同样输出当前文件的完整路径 大家可以去掉注释 测试一下
filebean.setFileSize(new FileInputStream(array[i]).available());
}
fileList.add(filebean);
}
System.out.println("fileList"+fileList.toString());
model.addAttribute("modelFileList", fileList);
}
}
return "uploadFile/uploadFilelist";
}
@RequestMapping("/dotextdownload")
@ResponseBody
public String dotextdownload(@RequestParam String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException{
try(ServletOutputStream outputStream = response.getOutputStream()){
String filePath =request.getSession().getServletContext().getRealPath("/temp/")+fileName;
// String filePath = request.getSession().getServletContext().getRealPath("/")+ fileName.getOriginalFilename();
// Files.copy(Paths.get(filePath), outputStream);
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename="+new String (fileName.getBytes("gb2312"),"ISO8859-1"));
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return "下载成功";
}