HSSFWorkbook读取excel并插入数据库

public String importChanel() throws IOException {
int countSucess=0;
int countFail=0;
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("gbk");
response.addHeader("Content-Type", "text/html;charset=gbk");
path=URLDecoder.decode(request.getParameter("path"),"utf-8");

POIFSFileSystem fs = null;

HSSFWorkbook wb = null;

fs = new POIFSFileSystem(new FileInputStream(path));

wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheetAt(0);

HSSFRow row = null;

HSSFCell cell = null;

TbChnlIinfoM chnlIinfoM=new TbChnlIinfoM();

int rowNum, cellNum;

int i;

String errorString="";

String alertString="请检查对应行的渠道编码是否已存在,并且保证Excel文档中数据格式是文本类型!";

rowNum = sheet.getLastRowNum();


for (i = 1; i <= rowNum; i++) {

row = sheet.getRow(i);

cell = row.getCell((short) 0);

chnlIinfoM.setStatisMonth(cell.getStringCellValue());

cell = row.getCell((short) 1);

chnlIinfoM.setCountyName(cell.getStringCellValue());

cell = row.getCell((short) 2);

chnlIinfoM.setName(cell.getStringCellValue());

cell = row.getCell((short) 3);

chnlIinfoM.setId(cell.getStringCellValue());

cell = row.getCell((short) 4);

chnlIinfoM.setPrncpArea(cell.getStringCellValue());

cell = row.getCell((short) 5);

chnlIinfoM.setPrncpChnlId(cell.getStringCellValue());

cell = row.getCell((short) 6);

chnlIinfoM.setPrncpChnlName(cell.getStringCellValue());

cell = row.getCell((short) 7);

chnlIinfoM.setPnncpChnlType(cell.getStringCellValue());

if (chnlIinfoM.getPrncpChnlId()!=null&&!"".equals(chnlIinfoM.getPrncpChnlId())&&Service.isExistPId(chnlIinfoM.getPrncpChnlId())==false) {
if(chnlIinfoM.getCountyName()==quanXianCountyName||quanXianCountyName.equals(chnlIinfoM.getCountyName())){
if (Service.saveOrUpdateCnl(chnlIinfoM)) {

countSucess=countSucess+1;
}else {

if (errorString=="") {
errorString=""+(i+1);
}else {
errorString=errorString+","+(i+1);
}
}
}
}else {

if (errorString=="") {
errorString=""+(i+1);
}else {
errorString=errorString+","+(i+1);
}
}
}

countFail=rowNum-countSucess;

PrintWriter printWriter = response.getWriter();
if (!"".equals(errorString)) {
printWriter.print("共"+rowNum+"条数据,成功:"+countSucess+"条,失败:"+countFail+"条!其中第"+errorString+"行导入失败!"+alertString);
}else {
printWriter.print("共"+rowNum+"条数据,成功:"+countSucess+"条,失败:"+countFail+"条!");
}

printWriter.flush();
printWriter.close();
return "importChanel";
}
[code="java"]
[/code]

你可能感兴趣的:(java)