使用poi导入excel文件数据到数据库

import com.coocaa.base.BaseAction;
import com.coocaa.base.CoocaaResponse;
import com.coocaa.config.ViewsConfig;
import com.coocaa.shop.goods.Goods;
import com.coocaa.shop.goods.GoodsService;
import com.coocaa.sys.user.AdminUser;
import com.coocaa.utils.ObjectUtil;
import com.coocaa.utils.Pager;
import com.coocaa.utils.StringUtils;
import com.coocaa.validator.Validator;
import com.coocaa.validator.propertyValidator.Rule;
import com.coocaa.validator.propertyValidator.ValidateException;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.System.currentTimeMillis;

@Controller
@RequestMapping("/ordergoodsComment")
public class OrdergoodsCommentAction extends BaseAction {

    @Autowired
 OrdergoodsCommentService ordergoodsCommentService;

 @RequestMapping("importComment")
    public String importComment(){

        return forward("importComment",ViewsConfig.shopviews);
 }


    @RequestMapping("insertImportComment")
    public String insertImportComment(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request) throws IOException, InvalidFormatException, ParseException {
        if (multipartFile.isEmpty()){
            return error("您的文件未上传");
 }else {
            if (!multipartFile.getOriginalFilename().endsWith(".xls")){
                return error("请上传excel文件");
 }

            Workbook workbook = WorkbookFactory.create(multipartFile.getInputStream());
 Sheet sheet = workbook.getSheetAt(0);
 int rows = sheet.getLastRowNum();
 int colsCount=6;
 for (int row_=0;row_<=rows;row_++){
                Row row = sheet.getRow(row_);
 String[] sheetObj  = new String[colsCount];
 for (int col=0;col;col++) {
                    Cell cell = row.getCell(col);
 if (cell == null) {
                        sheetObj[col] = "";
 continue;
 }
                    switch (cell.getCellType())
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            if(HSSFDateUtil.isCellDateFormatted(cell)){//处理日期、时间格式
 SimpleDateFormat sdf = null;
 if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("m/d/yy")) {
                                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 Date date = cell.getDateCellValue();
 sheetObj[col]=sdf.format(date);
 }
                            }else{
                            sheetObj[col]=cell.getNumericCellValue()+"";
 }
                            break;
 case Cell.CELL_TYPE_STRING:
                            sheetObj[col]=cell.getStringCellValue()+"";
 break;
 default:
                            sheetObj[col]="";
 }
                }
                //处理结果,插入数据库中
 OrdergoodsComment ordergoodsComment = new OrdergoodsComment();
 ordergoodsComment.setGoodsId((int) Float.parseFloat(sheetObj[0]));
 ordergoodsComment.setGoodsName(sheetObj[1]);
 ordergoodsComment.setUserName(sheetObj[2]);

 Long createTime = null;
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 if (StringUtils.isEmpty(sheetObj[3])) {
                    createTime = currentTimeMillis() / 1000;
 } else {
                    try {
                        createTime = sdf.parse(sheetObj[3]).getTime() / 1000;
 } catch (ParseException e) {
                        e.printStackTrace();
 createTime = 0l;
 }
                }
                ordergoodsComment.setCreateTime(createTime.intValue());

 if (StringUtils.isNumeric(sheetObj[4])){
                ordergoodsComment.setGrade(Integer.parseInt(sheetObj[4]));
 }else {
                    ordergoodsComment.setGrade(5);
 }
                ordergoodsComment.setContent(sheetObj[5]);

 //处理其他非空数据库非空字段
 ordergoodsComment.setOrderId(0);
 ordergoodsComment.setOrderSn("0");
 ordergoodsComment.setPayTime(0);
 ordergoodsComment.setSensation(",外观时尚,送货快,画面清晰,清晰度不错");
 ordergoodsComment.setIsAuditing(1);
 ordergoodsComment.setAuditingTime(0);
 ordergoodsComment.setUserId(0);
 ordergoodsComment.setParentId(0);
 ordergoodsComment.setIsDelete(0);
 ordergoodsComment.setIsEssence(0);

 ordergoodsCommentService.saveOrUpdate(ordergoodsComment);

 }
 multipartFile.getInputStream().close();

 }
        return redirect("adminCommentList.cc");
 }
}

 

pom.xml配置:


 org.apache.poi
 poi
 ${poi.version}

你可能感兴趣的:(java)