HSSFWorkbook读取excel并插入数据库

本文介绍了一个Java程序,该程序用于从Excel文件中批量导入渠道信息到数据库。文章详细展示了如何读取Excel表格中的数据并将其转换为Java对象,然后保存到数据库的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值