开发者社区> 问答> 正文

求POI 3.1 实现读取带有合并单元格的excel:报错

POI 3.1 实现读取带有合并单元格的excel。看官网上的版本历史还没有看到低版本的这个实现,有人做过可以帮忙 给一个实现方式么

展开
收起
kun坤 2020-06-06 16:19:26 566 0
1 条回答
写回答
取消 提交回答
  • 对于每个Cell,如果不是合并单元格中的Cell或者是合并单元格的第一个Cell,则处理该Cell的数据。######没明白呢,希望贴个例子
    ######

    String url=req.getSession().getServletContext().getRealPath("/"); String path = url+"\excelModel\tolls\beltwayPreferentialMonth.xls"; OutputStream ouputStream = null; HSSFWorkbook workbook=	null;//接收到的报表对象 InputStream inputStream; try { inputStream = new FileInputStream(path); workbook = new HSSFWorkbook(inputStream); HSSFSheet sheet = workbook.getSheetAt(0); res.setContentType("application/vnd.ms-excel;");
    res.setHeader("Content-disposition", "attachment;filename="+ new String(("绕城优惠情况月汇总.xls").getBytes("GB2312"), "ISO8859_1"));// 设定输出文件头 ouputStream = res.getOutputStream();
    workbook.write(ouputStream);

    	} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			try {
    				ouputStream.flush();
    				ouputStream.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}    
    		}</pre> 
    



    ######

    我自己实现了这功能:贴出代码给大家参考一下

    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import javax.servlet.http.HttpServletRequest;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.util.Region;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.struts.upload.FormFile;

    import com.boco.eoms.base.util.ApplicationContextHolder;
    import com.boco.eoms.base.util.StaticMethod;
    import com.boco.eoms.base.util.UUIDHexGenerator;
    import com.boco.eoms.commons.system.session.form.TawSystemSessionForm;
    import com.boco.eoms.partner.inspect.mgr.ICheckTemplateItemMgr;
    import com.boco.eoms.partner.inspect.model.CheckTemplateItem;
    import com.boco.eoms.partner.netresource.util.XLSToFormFileImport;
    import com.informix.util.stringUtil;
    import com.sun.syndication.feed.sse.Update;
    /**
     * Description: 模板导入方法
     * @author wyk
     * @since 2016-09-08
     *
     */
    public class CheckItemExcelUtil {

        

          private POIFSFileSystem fs;
          private HSSFWorkbook wb;
          private HSSFSheet sheet;
          private HSSFRow row;
          private static List<String> findName = new ArrayList();
          private static List<String> point = new ArrayList();
          private static String dir;
          private static String out;

          public void dealExcel(FormFile file,HttpServletRequest request) throws Exception
          
          {
            try
            {     
              List content = new ArrayList();
              try {
                this.fs = new POIFSFileSystem(file.getInputStream());
                this.wb = new HSSFWorkbook(this.fs);
              } catch (IOException e) {
                e.printStackTrace();
              }
              //获得基础数据
              String nowDate = StaticMethod.getCurrentDateTime();
              String bigItemId=StaticMethod.null2String(request.getParameter("bigItemId"));//模板大项id
              String templateId=StaticMethod.null2String(request.getParameter("templateId"));//模板项id
              String specialty = StaticMethod.null2String(request.getParameter("specialty"));//自建专业字典
              String templateType = StaticMethod.null2String(request.getParameter("templateFlag"));//类型
              TawSystemSessionForm sessionForm = (TawSystemSessionForm) request.getSession().getAttribute("sessionform");
              ICheckTemplateItemMgr service = (ICheckTemplateItemMgr) ApplicationContextHolder.getInstance().getBean("checkTemplateItemMgr");
              for (int n = 0; n < wb.getNumberOfSheets(); n++) {//获取每个Sheet表
                  if("1124101".equals(specialty)){//配套
                      //取第一个sheet
                      n=0;
                  }
                  if("1124102".equals(specialty)){//不配套
                      //取第二个sheet
                      n=1;
                  }
                  if("1124103".equals(specialty)){//铁塔
                      //取第三个sheet
                      n=2;
                  }
                  if("1124104".equals(specialty) && "1124105".equals(specialty)){//室分及WLAN
                      //取第四个sheet
                      n=3;
                  }
                  if("1124106".equals(specialty)){//传输线路
                      //取第⑤个sheet
                      n=4;
                  }
                  if("1124107".equals(specialty)||"1124105".equals(specialty)){//集客家客
                      //取第六个sheet
                      n=5;
                  }
                  Map<String,Object> map = new HashMap<String,Object>();//map 存放所有的
                  Map<String,Object> map1 = new HashMap<String,Object>();//map1存放所有合并单元格的
                  sheet=wb.getSheetAt(n);//获取第几个sheet
                  int rowNum = this.sheet.getLastRowNum();//得到最后列数,用于循环
                  this.row = this.sheet.getRow(0);
                  //处理当前sheet所有的有合并的单元格
                  this.sheet.getNumMergedRegions();//获取所有合并过的单元格从0开始的(读取顺序为从上到下)
                  for(int num=0;num< this.sheet.getNumMergedRegions();num++){//第一个是合并的excel名称不需要管       
                      Region region = sheet.getMergedRegionAt(num);//得到这个合并单元格的对象
                      String temp="";
                      for (int row = region.getRowFrom(); row <= region.getRowTo(); row++) {
                          for (short col = region.getColumnFrom(); col <= region.getColumnTo(); col++){
                              temp= getCellFormatValue(this.sheet.getRow(region.getRowFrom()).getCell(col)).trim();//要将每个单元格的值都存为和第一个一样的就在读值的时候不变唯一的列标
                              map1.put(row+"#"+col, temp);
                              if (row ==0 && col==0) {
                                  map1.put(row+"#"+1, temp);
                                  map1.put(row+"#"+2, temp);
                                  map1.put(row+"#"+3, temp);
                                  map1.put(row+"#"+4, temp);
                                  map1.put(row+"#"+5, temp);
                                  break;
                                  }
                              }
                          }
                      }
                  //System.out.println("map1的size为"+map1.size());
                  //按照正常的轮巡定位单个单元格
                  for (int i = 1; i < rowNum; i++) {
                    this.row = this.sheet.getRow(i);
                    for (int j = 0; j < this.row.getPhysicalNumberOfCells()-2; j++) {
                      String temp = getCellFormatValue(this.row.getCell(j)).trim();
                        point.add(i + "," + j);
                        findName.add(temp);
                        //System.out.println(i +1+ "," + (j +1)+ "         " + temp);
                            map.put(i+"#"+j, temp);
                        }
                  }
                 
                  map.putAll(map1);//得到每个sheet 的所有单元格的值
                  //System.out.println(map);
                  //反过来循环打印
                  CheckTemplateItem checkItem = new CheckTemplateItem();
                  //如果该条记录id 为null,就应该新增一条
                  String id="";
                  try {
                    if(map.containsValue(" ")){
                          //不存储报错哪一个单元格为空提示
                          String value="";
                          for(int k=1;k<rowNum;k++){
                              for(int m =0;m<6;m++){
                                   value = StaticMethod.nullObject2String(map.get(k+"#"+m));
                                  if("".equals(value)){
                                     System.out.println("第"+k+"行第"+m+"列数据为空");
                                  }
                                  if (" ".equals(value)) {
                                      System.out.println("第"+k+"行第"+m+"列数据是空格");
                                  }else{
                                      System.out.println("第"+k+"行第"+m+"列数据是"+value);
                                }
                              }
                              
                          }
                      }else{//当这个单元格无空值的时候才存值
                          for(int k=2;k<rowNum;k++){//第一列到第六列
                              checkItem = service.geTemplateItemByCondition(map.get(k+"#0").toString(), map.get(k+"#1").toString(), map.get(k+"#2").toString(),templateType);
                              if (checkItem.getId() ==null || checkItem.getId()=="") {
                                  id = UUIDHexGenerator.getInstance().getID();
                                  checkItem.setId(id);
                                  checkItem.setBigitemName(map.get(k+"#0").toString());//bigitemName 设备类别
                                  checkItem.setCheckItem(map.get(k+"#1").toString());//抽检项目
                                  checkItem.setRequirement(map.get(k+"#2").toString());//要求
                                  checkItem.setBigitemId(bigItemId);//模板大项id,记录归属的id
                                  checkItem.setTemplateId(templateId);
                                  checkItem.setAddTime(nowDate);
                                  checkItem.setAddUser(sessionForm.getUserid());
                                  checkItem.setStatus(1);
                            }
                              checkItem.setBasePoints(Integer.parseInt(map.get(k+"#3").toString().substring(0, map.get(k+"#3").toString().trim().length()-2)));//基分
                              checkItem.setEvaluationStandards(map.get(k+"#4").toString());//评分标准
                              checkItem.setAnotherName(map.get(k+"#5").toString());//别名
                              service.save(checkItem);
                              
                          }
                      }
                    service.updateItemNum(templateId);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(n>=0){
                    break;
                }
              }
            }
            catch (Exception e)
            {
              System.out.println("读取文件内容出错");
              e.printStackTrace();
            }
          }

          /**获取单元格数据*/
          private String getCellFormatValue(HSSFCell cell)
          {
            String cellvalue = "";
            if (cell != null)
            {
              switch (cell.getCellType())
              {
              case 0:
              case 2:
                if (HSSFDateUtil.isCellDateFormatted(cell))
                {
                  Date date = cell.getDateCellValue();
                  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                  cellvalue = sdf.format(date);
                }
                else
                {
                  cellvalue = String.valueOf(cell.getNumericCellValue());
                }
                break;
              case 1:
                cellvalue = cell.getRichStringCellValue().getString();
                break;
              default:
                cellvalue = " ";

                break; }
            } else cellvalue = "";

            return cellvalue;
          }
          

    }

    2020-06-06 16:19:31
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载