Java怎样从Excel文件中读取数据

用Java怎样从Excel文件中读取数据
package cn.com.spaceware.lixun;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import cn.com.spaceware.sxd.SC_BANK_DATABASE.DATABEAN.RepairInfoBean;


/**
* 从Excel文件中读取ATM机维护信息
*
* Author: Shune LEE
*
* Date: November 22nd,2005
*/

public class ReadRepairInfo{

private boolean isCancel=false;        //控制读取是否继续进行的参数
private String filePath=null;          //Excel文件的存放全路径

/*控制格式的变量*/
private int headNum=2;   //控制从第headNum行开始读取,因为行的索引是从0开始的
private int leftNum=0;   //控制从第leftNum列开始读取,因为列的索引是从0开始的


ReadRepairInfo(String file){
     this.filePath=file;
}


/**
  *
  * @author Shune Lee
  *
  * TODO 从Excel文件中读取维护信息,并添加到RepairInfoBean中去
  *
  */
public ArrayList readExcel4RepairInfo(){
     ArrayList table=new ArrayList();
     ArrayList record=new ArrayList();
     
     try {
         
            HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(filePath));
            HSSFSheet sheet = workbook.getSheetAt(0);    //得到一个Sheet
            
            /*获得导入的记录数,也就是数据的行数*/
            int rowNum=(sheet.getLastRowNum()-sheet.getFirstRowNum()+1)-headNum;  //行的索引是从0开始的
            
            /*遍历所有数据,并将得到的数据传给rInfo*/
            for(int i=headNum;i
                /*如果用户将isCancel设为true,则停止读取*/
                if(isCancel)
                    break;
               
                HSSFRow row = sheet.getRow(i);
               
                for(short j=row.getFirstCellNum();j
                    String cellContent1=null;
                    Double cellContent2=null;
                    HSSFCell cell=row.getCell(j);
                    
                    /*判断单元格内容的类型,并赋给相应的变量*/
                    if(cell.getCellType()==1){
                        cellContent1=cell.getStringCellValue();
                        record.add(cellContent1);
                    }
                    else if(cell.getCellType()==0){
                        cellContent2=new Double(cell.getNumericCellValue());
                        record.add(cellContent2);
                    }
                    else
                        System.out.println("Excel中的数据有问题,请检查。");
                }
                table.add(getRepairInfoBean(record));
            }
            
        } catch (FileNotFoundException e) {
            System.out.println("找不到文件 " + filePath);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("访问文件出错 " + filePath);
            e.printStackTrace();
        }
     
     return table;
}

/**
  *
  * @author Shune Lee
  *
  * TODO 用从Excel读取的记录生成RepairInfoBean
  *
  * @param ArrayList    从Excel读取的一条记录,即一行
  */
public RepairInfoBean getRepairInfoBean(ArrayList content){
     RepairInfoBean rpInfo=new RepairInfoBean();
     
     if(content!=null&&!(content.isEmpty())){
         
         /*给RepairInfoBean的对象传入数据*/
         rpInfo.setRepairID(((Double)content.get(0)).intValue());
         rpInfo.setStrATMEndCode(((Double)content.get(1)).intValue());
         rpInfo.setDEPLOYID(((Double)content.get(2)).intValue());
         rpInfo.setStrRepairType(((Double)content.get(3)).intValue());
         rpInfo.setStrContent((String)content.get(4));
         rpInfo.setStrPersonName((String)content.get(5));
         rpInfo.setStrDate(new String().valueOf(content.get(6)));
         System.out.println("The size is="+content.size());
     }
        
     return rpInfo;
}


/*测试函数*/
public static void main(String[] args){
     ReadRepairInfo readRepairInfo=new ReadRepairInfo("E://test.xls");
     
     ArrayList list=readRepairInfo.readExcel4RepairInfo();
     
     Iterator it=list.iterator();
     while(it.hasNext()){
         RepairInfoBean rpInfo=(RepairInfoBean)it.next();
         System.out.println("RepairID="+rpInfo.getRepairID()+"; "+"strContent="+rpInfo.getStrContent());
     }
}


} 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SSM(Spring + Spring MVC + MyBatis)是一种常用的Java Web开发框架,它可以用来处理Web请求和数据库操作。要使用SSM读取Excel文件数据,可以按照以下步骤进行操作: 1. 引入相关依赖:在项目引入Spring、Spring MVC、MyBatis和Apache POI等相关的依赖。Apache POI是一个用于处理Excel文件Java库。 2. 创建数据模型类:创建一个数据模型类,用于表示Excel文件数据。该类应该包含与Excel单元格对应的属性,以便于在MyBatis映射数据。 3. 创建Excel读取器:使用Apache POI库创建一个Excel读取器,用于读取Excel文件数据。读取器可以读取整个Excel文件,并将其内容加载到内存,以便于后续处理。 4. 创建MyBatis映射文件:创建一个MyBatis映射文件,用于定义如何从数据模型类获取数据并将其存储到数据。映射文件应该定义与Excel文件的每一行相对应的SQL语句。 5. 编写DAO层代码:创建一个DAO层类,用于实现与数据库的交互。在该类,可以使用MyBatis提供的注解或XML配置文件来定义SQL语句,并将Excel文件数据插入到数据库表。 6. 调用DAO层方法:在控制器调用DAO层方法,并将Excel文件作为参数传递给该方法。DAO层方法将读取Excel文件数据,并将其插入到数据库表。 以下是一个简单的示例代码,展示了如何使用SSM读取Excel文件数据: 1. 在Spring配置文件添加依赖: ```java <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.1.0</version> </dependency> ``` 2. 创建数据模型类: ```java public class ExcelData { private int id; private String name; private double score; // getter和setter方法 } ``` 3. 创建Excel读取器: ```java public class ExcelReader { public List<ExcelData> readExcel(File excelFile) throws IOException { List<ExcelData> dataList = new ArrayList<>(); try (Workbook workbook = WorkbookFactory.create(excelFile)) { Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { ExcelData data = new ExcelData(); data.setId(Integer.parseInt(row.getCell(0).getStringCellValue())); data.setName(row.getCell(1).getStringCellValue()); data.setScore(Double.parseDouble(row.getCell(2).getStringCellValue())); dataList.add(data); } } catch (Exception e) { e.printStackTrace(); } return dataList; } } ``` 4. 创建MyBatis映射文件:根据Excel文件数据结构,创建相应的MyBatis映射文件。这里不再赘述。 5. 编写DAO层代码:创建一个DAO层类,并使用MyBatis注解或XML配置文件来定义SQL语句。示例代码如下: ```java @Mapper public interface ExcelDataMapper { @Insert("INSERT INTO student (id, name, score) VALUES (#{id}, #{name}, #{score})") void insertData(@Param("data") ExcelData data); } ``` 6. 在控制器调用DAO层方法:将Excel文件作为参数传递给DAO层方法,并将读取的数据插入到数据库表。示例代码如下: ```java @RestController public class ExcelController { @Autowired private ExcelDataMapper excelDataMapper; @PostMapping("/readExcel") public List<ExcelData> readExcel(@RequestParam("file") MultipartFile file) throws IOException { File excelFile = new FileSystemResource(file.getInputStream()); List<ExcelData> dataList = excelDataMapper.readExcel(excelFile); return dataList; } } ``` 以上代码仅为示例,实际应用需要根据具体需求进行修改和完善。另外,还需要考虑如何将数据插入到数据库表的安全性、效率和性能等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值