自己写的例子:
/**
* add a contact_member
*/
package com.lawstar.lxdx.service;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 com.lawstar.lxdx.dao.ContactMemberDAO;
import com.lawstar.lxdx.pojo.ExportMemberPOJO;
import com.lawstar.lxdx.util.Tools;/**
* @author sunny
*
*/
public class ImportContactMemberServlet extends BaseService { private static final long serialVersionUID = 1L;
public String filepath ;
public void init() throws ServletException {
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String group = request.getParameter("groups");
String []groups = group.split(",");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查是否是一个文件上传请求
if (isMultipart) {
//设置filepath
filepath = getServletContext().getRealPath("/cac") ;
//从request中读取excel表格,保存到服务器
uploadExcelFromRequest(request);
//将联系方式导入到数据库中,不合格的存到List中
List<ExportMemberPOJO> exportList = exportListFromExcel( groups);
if(exportList==null||0==exportList.size()||exportList.isEmpty()){
//都成功
response.sendRedirect("/jsp/import_member.jsp?export=unexport");
}else{
//将不合格的联系方式写到export.xls中
exportListToExcel(exportList);
response.sendRedirect("/jsp/import_member.jsp?export=export");
}
} else {
response.sendRedirect("/jsp/import_member.jsp?export=noupload");
}
} public void destroy() {
this.closeConn();
}
/**
* 将不合格的联系方式写到export.xls中
* @param exportList
*/
public void exportListToExcel(List<ExportMemberPOJO> exportList){
File srcFile = new File(filepath + File.separator );
if (!srcFile.exists()) {
srcFile.mkdir();
}
HSSFWorkbook wbEx = new HSSFWorkbook();//初始化
HSSFSheet sheetEx = wbEx.createSheet("不合格通讯方式");//新建,命名一个工作单
sheetEx.setColumnWidth((short)0,(short)2000);
sheetEx.setColumnWidth((short)1,(short)3000);
sheetEx.setColumnWidth((short)2,(short)3000);
HSSFRow row = sheetEx.createRow((short) 0);//创建第一行
row.createCell((short) 0).setCellValue(new HSSFRichTextString("姓名"));
row.createCell((short) 1).setCellValue(new HSSFRichTextString("电话"));
row.createCell((short) 2).setCellValue(new HSSFRichTextString("未添加原因"));
int size = exportList.size();
for (int e=0 ;e<size;e++){
ExportMemberPOJO ex = exportList.get(e);
HSSFRow addRow = sheetEx.createRow((short) (e+1));//创建第一行
addRow.createCell((short) 0).setCellValue(new HSSFRichTextString(ex.getUsername()));
addRow.createCell((short) 1).setCellValue(new HSSFRichTextString(ex.getTelephone()));
addRow.createCell((short) 2).setCellValue(new HSSFRichTextString(ex.getMessage()));
}
FileOutputStream fileOut;
//把生成的文件写到服务器上
try {
fileOut = new FileOutputStream(filepath + File.separator + "export.xls");
wbEx.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将联系方式导入到数据库中,不合格的存到List中,返回
* @return
*/
public List<ExportMemberPOJO> exportListFromExcel(String [] groups){
//读取import.xls文件中的数据同时生产export.xls文件
FileInputStream inputStream;
List<ExportMemberPOJO> exportList = new ArrayList();
try {
inputStream = new FileInputStream(filepath + File.separator + "import.xls");
ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = inputStream.read(buffer)) != -1)
byteOS.write(buffer, 0, count);
byteOS.close();
byte[] allBytes = byteOS.toByteArray();
// create workbook from array:
ByteArrayInputStream byteIS = new ByteArrayInputStream(allBytes);
HSSFWorkbook wb = new HSSFWorkbook(byteIS);
HSSFSheet sheet = wb.getSheetAt(0);
// this.conn = getConn();
conn.setAutoCommit(false);
int rows = sheet.getPhysicalNumberOfRows();
for (int i=1;i< rows ;i++){
HSSFRow row = sheet.getRow(i);
int cells = row.getLastCellNum();
HSSFCell nameCell = row.getCell((short)0);
HSSFCell telCell = row.getCell((short)1);
String username = nameCell.getRichStringCellValue().getString();
String telephone = String.valueOf((int)telCell.getNumericCellValue());
ContactMemberDAO cmdao = new ContactMemberDAO(this.conn);
int has = cmdao.hasThisMember(username, telephone);
switch (has) {
case 0: {//可以添加
boolean suc = cmdao.insertMember(username, telephone,groups);
break;
}
case 1:{//
ExportMemberPOJO exportMember = new ExportMemberPOJO();
exportMember.setTelephone(telephone);
exportMember.setUsername(username);
exportMember.setMessage("该人名已有,请单独添加。谢谢合作!");
exportList.add(exportMember);
break;
}
case 2: {
ExportMemberPOJO exportMember = new ExportMemberPOJO();
exportMember.setTelephone(telephone);
exportMember.setUsername(username);
exportMember.setMessage("通讯录中已经有此手机号,不能添加");
exportList.add(exportMember);
break;
}
case 3:
break;
default:
break;
}
}
conn.commit();
return exportList;
} catch(SQLException se){
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}catch (Exception e) {
e.printStackTrace();
}
finally {
return exportList;
}
}
public void uploadExcelFromRequest(HttpServletRequest request){
DiskFileItemFactory dff = new DiskFileItemFactory();// 创建该对象
dff.setRepository(new File(filepath));// 指定上传文件的临时目录
dff.setSizeThreshold(1024000000);// 指定在内存中缓存数据大小,单位为byte
ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
sfu.setFileSizeMax(2100000000);// 指定单个上传文件的最大尺寸
sfu.setSizeMax(1000000000);// 指定一次上传多个文件的总尺寸
FileItemIterator fii;
try {
fii = sfu.getItemIterator(request);
// 解析request请求,并返回FileItemIterator集合
while (fii.hasNext()) {
FileItemStream fis = fii.next();// 从集合中获得一个文件流
if (!fis.isFormField() && fis.getName().length() > 0) {// 过滤掉表单中非文件域
//---------------------文件传到服务器---------------------
BufferedInputStream in = new BufferedInputStream(fis.openStream());// 获得文件输入流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filepath + File.separator + "import.xls")));// 获得文件输出流
Streams.copy(in, out, true);// 开始把文件写到你指定的上传文件夹
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}