java读取表格数据,现成方法调用

 java读取表格数据,方法已封装好,多数情况下能够直接调用,再对返回的值进行操作。需要进行改动的根据情况进行改动。

1.导入包

需要导入下面三个包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17-beta1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17-beta1</version>
</dependency>

2.代码

public class Excel(){

public List<Map<String,String>>  read(String filePath,String columns[]) {
        Workbook wb =null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;

        wb = readExcel(filePath);
        if(wb != null){
            //用来存放表中数据
            list = new ArrayList<Map<String,String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数 
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i<rownum; i++) {
                Map<String,String> map = new LinkedHashMap<String,String>();
                row = sheet.getRow(i);
                if(row !=null){
                    for (int j=0;j<colnum;j++){
                        cellData =   getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                }else{
                    break;
                }
                list.add(map);
            }
        }
        
        return list;
       
    }
    //读取excel
    public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try { is = new FileInputStream(filePath);
        if(".xls".equals(extString)){
            return wb = new HSSFWorkbook(is);
        }else if(".xlsx".equals(extString)){
            return wb = new XSSFWorkbook(is);
        }else{
            return wb = null;
        }
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return wb;
}
@SuppressWarnings("deprecation")
public static String getCellFormatValue(Cell cell){
	 String cellValue = "";  
     if(cell == null){  
         return cellValue;  
     }  
     //把数字当成String来读,避免出现1读成1.0的情况  
     
     if(cell.getCellType()==0) {
    	 Date d=cell.getDateCellValue();
    	 //如果是时间,则转为yyyy-MM-dd的格式。可以根据自己的需要转化
    	 DateFormat df= new SimpleDateFormat("yyyy-MM-dd");
    	 cellValue=df.format(d);
     }else {
    	 if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){  
             cell.setCellType(Cell.CELL_TYPE_STRING);  
         }  
       switch (cell.getCellType()){  
         case Cell.CELL_TYPE_NUMERIC: //数字  
             cellValue = String.valueOf(cell.getNumericCellValue());  
             break;  
         case Cell.CELL_TYPE_STRING: //字符串  
             cellValue = String.valueOf(cell.getStringCellValue());  
             break;  
         case Cell.CELL_TYPE_BOOLEAN: //Boolean  
             cellValue = String.valueOf(cell.getBooleanCellValue());  
             break;  
         case Cell.CELL_TYPE_FORMULA: //公式  
             cellValue = String.valueOf(cell.getCellFormula());  
             
             break;  
         
         case Cell.CELL_TYPE_BLANK: //空值   
             cellValue = "";  
             break;  
         case Cell.CELL_TYPE_ERROR: //故障  
             cellValue = "非法字符";  
             break;  
         default:  
             cellValue = "未知类型";  
             break;  
     }  
     }
     return cellValue; 
}
}

方法说明:读者只需调用 read() 方法,该方法读表时已设置为忽略第一行表头,传入参数filePath:表格的文件地址,

String columns[] 表格中每个字段对应的名字,读者可自行取值,顺序相同即可。返回值为以 字段名为键值,字段值 为值的,map型链表。键值为column[]中的字符值。将所有的类型都转化为了String,读者在取值是可根据类型转换回来。

下面是一个调用和对返回的值处理 示例:

 String c[]= {"stuId","stuName","orgName","orgClass"};
    	 List<Map<String,String>> list=read(filePath,c);
    	 DateFormat df= new SimpleDateFormat("yyyy-MM-dd");
         for (Map<String,String> map : list) {
           String stuId=map.get("stuId");
           String stuName=map.get("stuName");
           String orgName=map.get("orgName");
           String orgClass=map.get("orgClass"); 
        
         }

谢谢阅读 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java代码可以使用Apache POI库来读取表格中的数据。下面是一个简单的示例: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; public class ExcelReader { public static void main(String[] args) { try { // 打开表格文件 FileInputStream file = new FileInputStream(new File("path/to/your/excel/file.xlsx")); // 创建工作簿对象 Workbook workbook = WorkbookFactory.create(file); // 选择第一个工作表 Sheet sheet = workbook.getSheetAt(0); // 遍历每一行 for (Row row : sheet) { // 遍历每个单元格 for (Cell cell : row) { // 根据单元格的类型读取数据 switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } // 关闭文件流 file.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在以上示例中,首先我们使用`FileInputStream`来读取Excel文件。然后创建`Workbook`对象,通过`WorkbookFactory.create()`方法读取工作簿中的数据。 然后,我们选择第一个工作表,通过遍历每一行来读取表格中的数据。对于每个单元格,根据单元格的类型使用`getCellType()`方法来判断数据类型,然后使用对应的方法(例如`getStringCellValue()`、`getNumericCellValue()`、`getBooleanCellValue()`)来读取数据。 最后,记得关闭文件流以释放资源。请注意,你需要根据你的实际需求和文件路径来修改代码中的文件路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值