Read Excel content (.xls, .xlsx) [from other blogs]

Recently, to import data into the database according to excel, you need to read the content of excel. A long time ago, I used jxl and poi two java libraries to operate excel, and the code was long lost. Temporarily found a piece of code from the Internet today, available. Record it here for later use.

The source address of the code:  http://blog.csdn.net/superdog007/article/details/48338337

 

import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
import java.util.Date;  
import java.util.HashMap;  
import java.util.Map;  
  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.DateUtil;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
import org.apache.poi.ss.usermodel.Workbook;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
/**
 * Read Excel
 *  
 * @author zengwendong
 */  
public class ReadExcelUtils {  
    private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);  
    private Workbook wb;  
    private Sheet sheet;  
    private Row row;  
  
    public ReadExcelUtils(String filepath) {  
        if(filepath==null){  
            return;  
        }  
        String ext = filepath.substring(filepath.lastIndexOf("."));  
        try {  
            InputStream is = new FileInputStream(filepath);  
            if(".xls".equals(ext)){  
                wb = new HSSFWorkbook(is);  
            }else if(".xlsx".equals(ext)){  
                wb = new XSSFWorkbook(is);  
            }else{  
                wb=null;  
            }  
        } catch (FileNotFoundException e) {  
            logger.error("FileNotFoundException", e);  
        } catch (IOException e) {  
            logger.error("IOException", e);  
        }  
    }  
      
    /**
     * Read the content of the Excel table header
     *  
     * @param InputStream
     * @return String array of header contents
     * @author zengwendong
     */  
    public String[] readExcelTitle() throws Exception{  
        if(wb==null){  
            throw new Exception("Workbook object is empty!");  
        }  
        sheet = wb.getSheetAt(0);  
        row = sheet.getRow(0);  
        // total number of header columns  
        int colNum = row.getPhysicalNumberOfCells();  
        System.out.println("colNum:" + colNum);  
        String[] title = new String[colNum];  
        for (int i = 0; i < colNum; i++) {  
            // title[i] = getStringCellValue(row.getCell((short) i));  
            title[i] = row.getCell(i).getCellFormula();  
        }  
        return title;  
    }  
  
    /**
     * Read Excel data content
     *  
     * @param InputStream
     * @return Map Map object containing cell data content
     * @author zengwendong
     */  
    public Map<Integer, Map<Integer,Object>> readExcelContent() throws Exception{  
        if(wb==null){  
            throw new Exception("Workbook object is empty!");  
        }  
        Map<Integer, Map<Integer,Object>> content = new HashMap<Integer, Map<Integer,Object>>();  
          
        sheet = wb.getSheetAt(0);  
        // get the total number of rows  
        int rowNum = sheet.getLastRowNum();  
        row = sheet.getRow(0);  
        int colNum = row.getPhysicalNumberOfCells();  
        // The body content should start from the second line, the first line is the title of the header  
        for (int i = 1; i <= rowNum; i++) {  
            row = sheet.getRow(i);  
            int j = 0;  
            Map<Integer,Object> cellValue = new HashMap<Integer, Object>();  
            while (j < colNum) {  
                Object obj = getCellFormatValue(row.getCell(j));  
                cellValue.put(j, obj);  
                j++;  
            }  
            content.put(i, cellValue);  
        }  
        return content;  
    }  
  
    /**
     *  
     * Set data according to Cell type
     *  
     * @param cell
     * @return
     * @author zengwendong
     */  
    private Object getCellFormatValue(Cell cell) {  
        Object cellvalue = "";  
        if (cell != null) {  
            // Determine the Type of the current Cell  
            switch (cell.getCellType()) {  
            case Cell.CELL_TYPE_NUMERIC:// If the Type of the current Cell is NUMERIC  
            case Cell.CELL_TYPE_FORMULA: {  
                // Determine whether the current cell is a Date  
                if (DateUtil.isCellDateFormatted(cell)) {  
                    // If it is a Date type, convert it to Data format  
                    // The data format is with hours, minutes and seconds: 2013-7-10 0:00:00  
                    // cellvalue = cell.getDateCellValue().toLocaleString();  
                    // The data format is without hours, minutes and seconds: 2013-7-10  
                    Date date = cell.getDateCellValue();  
                    cellvalue = date;  
                } else {// if it is a pure number  
  
                    // Get the value of the current Cell  
                    cellvalue = String.valueOf(cell.getNumericCellValue());  
                }  
                break;  
            }  
            case Cell.CELL_TYPE_STRING:// If the Type of the current Cell is STRING  
                // Get the current Cell string  
                cellvalue = cell.getRichStringCellValue().getString();  
                break;  
            default:// default Cell value  
                cellvalue = "";  
            }  
        } else {  
            cellvalue = "";  
        }  
        return cellvalue;  
    }  
  
    public static void main(String[] args) {  
        try {  
            String filepath = "F:test.xls";  
            ReadExcelUtils excelReader = new ReadExcelUtils(filepath);  
            // Test for reading the title of the Excel table  
//          String[] title = excelReader.readExcelTitle();  
// System.out.println("Get the title of the Excel table:");  
//          for (String s : title) {  
//              System.out.print(s + " ");  
//          }  
              
            // Test for reading Excel table content  
            Map<Integer, Map<Integer,Object>> map = excelReader.readExcelContent();  
            System.out.println("Get the content of the Excel table:");  
            for (int i = 1; i <= map.size(); i++) {  
                System.out.println(map.get(i));  
            }  
        } catch (FileNotFoundException e) {  
            System.out.println("The file at the specified path was not found!");  
            e.printStackTrace ();  
        }catch (Exception e) {  
            e.printStackTrace ();  
        }  
    }  
}  

 Depends on two jars, namely:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326349843&siteId=291194637