SSM上传EXCLE到数据库 和 从数据库导出为EXCLE
package com.ABC.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import com.ABC.pojo.NewStudent;
import com.ABC.service.NewStudentInfoService;
@Controller
public class FileUploadController {
@Autowired
private NewStudentInfoService newStudentInfoService;
@RequestMapping("/importexcel")
public String upLoadExcle(MultipartFile file, HttpServletRequest request, Model model) throws Exception {
System.out.println("你来上传了啊!===>");
// 获取服务器端路径
String path = request.getServletContext().getRealPath("upload");
System.out.println("获取服务器端路径path==>" + path);
// 获取到上传文件名称
String fileName = file.getOriginalFilename();
System.out.println("获取到上传文件名称fileName==>" + fileName);
// 创建目标File
File targetFile = new File(path + "\\" + fileName);
System.out.println("创建目标targetFile==>" + targetFile);
// 创建存储目录
File targePath = new File(path);
System.out.println("创建存储目录targePath==>" + targePath);
// 判断服务器端目录是否存在,如果不存在创建
if (!targePath.exists()) {
targePath.mkdir();
}
// 把上传的文件存储到服务器端
file.transferTo(targetFile);
// 读取上传到服务器端的文件,遍历excle
Workbook workbook = WorkbookFactory.create(targetFile);
Sheet sheet = workbook.getSheet("Sheet1");
// 判断行数
int rownum = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rownum; i++) {
Row row = sheet.getRow(i);
// 判断单元格数量
int cellnum = row.getPhysicalNumberOfCells();
StringBuffer buf = new StringBuffer();
for (int j = 0; j < cellnum; j++) {
Cell cell = row.getCell(j);
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
buf.append(cell.getStringCellValue() + "~");
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
// 创建数字格式化工具类
DecimalFormat df = new DecimalFormat("####");
// 把从cell单元格读取到的数字,进行格式化防止科学计数法形式显示
buf.append(df.format(cell.getNumericCellValue()) + "~");
}
}
// 单元格循环完成后读取到的是一行内容
String hang = buf.toString();
String[] rows = hang.split("~");
NewStudent stu = new NewStudent();
stu.setName(rows[1]);
stu.setScore(Integer.valueOf(rows[2]));
stu.setPhone(rows[3]);
// System.out.println("上传学生信息:"+stu);
newStudentInfoService.saveStudent(stu);
}
return "success";
}
@RequestMapping(value = "downloadexcel")
public void downLoadExcel(HttpServletRequest request, HttpServletResponse response, Model model)
throws Exception, IOException {
// 查出所有的学生
List<NewStudent> stuList = newStudentInfoService.getAll();
// 获取服务端路径
String path = request.getServletContext().getRealPath("down");
String fileName = "testexcel.xlsx";
// 创建存储File
File targetFile = new File(path + "\\" + fileName);
// 创建存储目录
File targetPath = new File(path);
// 判断服务器端目录是否存在,如果不存在创建目录
if (!targetPath.exists()) {
targetPath.mkdir();
}
// 生成excle
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("学生成绩表");
int rowNum = 0;
for (NewStudent stu : stuList) {
XSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(stu.getId());
row.createCell(1).setCellValue(stu.getName());
row.createCell(2).setCellValue(stu.getScore());
row.createCell(3).setCellValue(stu.getPhone());
rowNum++;
}
// 把工作薄对象写入服务器磁盘
System.out.println("创建文件:" + targetFile);
workbook.write(new FileOutputStream(targetFile));
// 设置响应头
response.setContentType("application/x-xls;charset=GBK");
// 设定浏览器下载提示
response.setHeader("Content-Disposition",
"attachment;filename=\"" + new String(fileName.getBytes(), "ISO8859-1") + "\"");
//设置响应的文件的长度
response.setContentLength((int) targetFile.length());
//向响应文件流缓冲区写入文件
byte[] buff =new byte[4096];
BufferedOutputStream output = null;
BufferedInputStream input = null;
output = new BufferedOutputStream(response.getOutputStream());
input = new BufferedInputStream(new FileInputStream(targetFile));
//遍历文件
int len = 0;
while((len = input.read(buff))!=-1){
output.write(buff, 0, len);
}output.flush();
response.flushBuffer();
if(input!=null){
input.close();
}if(output!=null){
output.close();
}
}
}
response.setContentType(MIME)的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
例如web浏览器就是通过MIME类型来判断文件是GIF图片。通过MIME类型来处理json字符串。
Tomcat的安装目录\conf\web.xml 中就定义了大量MIME类型 ,可以参考。
response.setContentType("text/html; charset=utf-8"); html
.setContentType("text/plain; charset=utf-8"); 文本
text/javascript json数据
application/xml xml数据
这 个方法设置发送到客户端的响应的内容类型,此时响应还没有提交。给出的内容类型可以包括字符编码说明,例 如:text/html;charset=UTF-8.如果该方法在getWriter()方法被调用之前调用,那么响应的字符编码将仅从给出的内容类型 中设置。该方法如果在getWriter()方法被调用之后或者在被提交之后调用,将不会设置响应的字符编码,在使用http协议的情况中,该方法设 置 Content-type实体报头。
一般在Servlet中,习惯性的会首先设置请求以及响应的内容类型以及编码方式:
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType()的String参数及对应类型
value="image/bmp">BMP
value="image/gif">GIF
value="image/jpeg">JPEG
value="image/tiff">TIFF
value="image/x-dcx">DCX
value="image/x-pcx">PCX
value="text/html">HTML
value="text/plain">TXT
value="text/xml">XML
value="application/afp">AFP
value="application/pdf">PDF
value="application/rtf">RTF
value="application/msword">MSWORD
value="application/vnd.ms-excel">MSEXCEL
value="application/vnd.ms-powerpoint">MSPOWERPOINT
value="application/wordperfect5.1">WORDPERFECT
value="application/vnd.lotus-wordpro">WORDPRO
value="application/vnd.visio">VISIO
value="application/vnd.framemaker">FRAMEMAKER
value="application/vnd.lotus-1-2-3">LOTUS123
MIME映射策略就是在网页中使用哪个应用程序(即插件),打开哪种文件。另外还有使用权限问题。比如对PDF文档,用“application/pdf “策略。这在动态网页中很常见。出现这种现象,有两种情形:一是使用一个应用程序去打开它不能打开的文档,比如用在标签中定义“DWG”文档用 “application/pdf ”,就会出现无法打开的问题。二是文件扩展名符合要求,但文件内容(格式)不符合要求。你可以检查你浏览的网页源代码,获得出错信息。检查方法是:查看— 源文件。寻找类似于“application/pdf “的字符串,就可以看到,要打开的文件是否与应用程序匹配。 追问 如果不相匹配 如何解决回答 这通常是由网页编写人来更改。比如:你在源文件里面找到你要打开的文件的HTML标签,在里面加上应用程序即可。比如,你要在网页上打开一个PDF文档, 找到PDF文档那一行,在HTML标签里加上 type=“application/pdf “ 就可以了
Response.setHeader("Content-Disposition", "attachment; filename=" + fileName+".xls");
如果file.Name为中文则乱码。解决办法是
方法1:
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
下载的程序里有了上面一句,一般在IE6的下载提示框上将正确显示文件的名字,无论是简体中文,还是日文。但是文字只要超过17个字,就不能下载了。
一. 通过原来的方式,也就是先用URLEncoder编码,当中文文字超过17个时,IE6 无法下载文件。这是IE的bug,参见微软的知识库文章 KB816868 。原因可能是IE在处理 Response Header 的时候,对header的长度限制在150字节左右。而一个汉字编码成UTF-8是9个字节,那么17个字便是153个字节,所以会报错。而且不跟后缀也不对.
方法2:
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
在确保附件文件名都是简 体中文字的情况下,那么这个办法确实是最有效的,不用让客户逐个的升级IE。如果台湾同胞用,把gb2312改成big5就行。但现在的系统通常都加入了 国际化的支持,普遍使用UTF-8。如果文件名中又有简体中文字,又有繁体中文,还有日文。那么乱码便产生了。另外,在上Firefox (v1.0-en)下载也是乱码。