【代码】Excel导入到数据库

前言

        最近项目中需要将Excel中数据导入到数据库中,完成后,做一个代码总结。

代码

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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;

public class InsertExcel {
    /**
     * 解析方法
     * 
     * @param file
     * @return
     * @throws Exception
     */
    public List<String[]> getExcel(String filePath) throws Exception {
        // 创建对Excel工作簿文件的引用
        boolean isExcel2003 = filePath.toLowerCase().endsWith("xls") ? true : false;
        Workbook workbook = null;
        if (isExcel2003) {
            workbook = new HSSFWorkbook(new FileInputStream(new File(filePath)));
        } else {
            workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
        }
        // 在Excel文档中,第一张工作表的缺省索引是0
        // 其语句为:
        // HSSFSheet sheet = wookbook.getSheetAt(0);
        Sheet sheet = workbook.getSheet("T_POFO_ASSET");
        // 获取到Excel文件中的所有行数
        int rows = sheet.getPhysicalNumberOfRows();
        // 遍历行
        List<String[]> list_excel = new ArrayList<String[]>();
        for (int i = 1; i <= rows; i++) {
            // 读取左上端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // 获取到Excel文件中的所有的列
                int cells = row.getPhysicalNumberOfCells();
                String value = "";
                // 遍历列
                for (int j = 0; j <= cells; j++) {
                    // 获取到列的值
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_FORMULA:
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            value += cell.getNumericCellValue() + ",";
                            break;
                        case Cell.CELL_TYPE_STRING:
                            value += cell.getStringCellValue() + ",";
                            break;
                        default:
                            value += "0";
                            break;
                        }
                    }
                }
                String[] val = value.split(",");
                list_excel.add(val);
            }
        }
        workbook.close();
        return list_excel;
    }
}
入参:Excel文件完整路径。

出参:list<String[]>,每一行为一list,list中字段在字符串数组中。可根据具体的需要插入到list<实体>中。

总结

        输出参数后,之前还写过一篇博客,mybatis批量插入数据,入参为list,可以将此功能完成,在此不多叙述。

猜你喜欢

转载自blog.csdn.net/sds15732622190/article/details/79145981