POI读取Excel存入数据库

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;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class PoiRead {
//    public static void main(String[] args) throws Exception{

    public static List<List<String>> getResult() throws Exception {
        File filepath = new File("F:\\电子对抗.xlsx");
        InputStream is = new FileInputStream(filepath);
        //利用POI 把Excel表遍历生成List类型
        Workbook wb = new XSSFWorkbook(is);//对应一个Excel文件
        List<List<String>> sheetlist = new ArrayList<List<String>>();//对应一页sheet
        //对应第几张sheet,从0开始
        Sheet sheet = wb.getSheetAt(7);
        //获得行数
        int rowSize = sheet.getLastRowNum() + 1;
        for (int j = 0; j < rowSize; j++) {//遍历行
            Row row = sheet.getRow(j);
            if (row == null) {//略过空行
                continue;
            }
            int cellSize = row.getLastCellNum();//行中有多少个单元格,也就是有多少列
            List<String> rowList = new ArrayList<String>();//对应一个数据行,一行的数据
            for (int k = 0; k < cellSize; k++) {
                Cell cell = row.getCell(k);
                String value = null;
                if (cell != null) {
                    value = cell.toString();//内容转化字符串
                }
                rowList.add(value);
            }
            sheetlist.add(rowList);
        }
        return sheetlist;
    }

    //把原来长度为2的list拆分成成都为5的list,其中把第二个单元格的内容拆分成:title,author,cbs,ny.其中author.cbs,ny可能没有,title肯定有
    public static List<List<String>> newsheetlist(List<List<String>> sheetlist) {
        List<List<String>> newsheetlist = new ArrayList<List<String>>();
        for (int i = 0; i < sheetlist.size(); i++) {
            //异常检测很重要,一定要学会,少很多麻烦
            try {
            List<String> newrow = new ArrayList<String>();
            List<String> row = sheetlist.get(i);
            String category = row.get(0);
            String[] cutcategory = category.split(":|:");
            category = cutcategory[1].trim();
            newrow.add(category);
            //拆分单元格,把一个list的内容拆开
            String fourkinds = row.get(1);
            String[] splitfourkinds = fourkinds.split(":|:");
           //保证字段的完整,要进行判断是否有字段
                 /**
                 * 要保证list的size固定,由于可能有些字段没有,所以在每个字段应该出现的位置要进行判断,分两种情况,
                 * 一、出现,提取出来,不作处理
                 * 二、如果没有出现则,判断前一个字段是否它,如果是不作处理,如果不是要加入空内容。
                 * */
            String title =  " ";
            String author = " ";
            String publisher = " ";
            String ny = " ";
            int j = splitfourkinds.length;
            //肯定有title
            if (1 < j) {
                title = splitfourkinds[1];
                if(title.contains("作者")){
                    title = title.substring(0, title.length() - 2);
                }
                if (title.contains("出版")){
                    title = title.substring(0, title.length() - 3);
                }
                newrow.add(title);
            }
            //作者或者出版源
            if (2 < j) {
                if (splitfourkinds[1].contains("作者")){
                     author = splitfourkinds[2];
                    if (author.contains("出版源")){
                        author = author.substring(0, author.length() - 3);
                        author = author.replaceAll(" +","、");
                        author = author.substring(0,author.length()-1).trim();
                        newrow.add(author);
                    }
                    if (author.contains("出版社")){
                        author = author.substring(0, author.length() - 3);
                        author = author.replaceAll(" +","、");
                        author = author.substring(0,author.length()-1).trim();
                        newrow.add(author);
                    }
                    if (author.contains("作者")){
                        author = author.substring(0, author.length() - 2);
                        author = author.replaceAll(" +","、");
                        author = author.substring(0,author.length()-1).trim();
                        newrow.add(author);
                    }
                    if (author.contains("时间")){
                        author = author.substring(0, author.length() - 2);
                        author = author.replaceAll(" +","、");
                        author = author.substring(0,author.length()-1).trim();
                        newrow.add(author);
                    }
                    if (author.contains("出版时间")){
                        author = author.substring(0, author.length() - 4);
                        author = author.replaceAll(" +","、");
                        author = author.substring(0,author.length()-1).trim();
                        newrow.add(author);
                    }
                }
                //作者要么在第二位,要么不出现,缺少作者要补充添加空字段
                if (splitfourkinds[1].contains("出版源")){
                    newrow.add(author);
                    publisher = splitfourkinds[2].trim();
                    if (publisher.contains("时间")){
                        publisher = publisher.substring(0,publisher.length()-2);
                    }
                    newrow.add(publisher);
                }
            }
            //可能是出版社或时间
            if (3 < j) {
                //如果是“时间”,要判断前一个是否有“出版社”字段,没有就补充
                if (splitfourkinds[2].contains("时间")){
                    if (!splitfourkinds[1].contains("出版")){
                        newrow.add(publisher);
                    }
                    ny = splitfourkinds[3].trim();
                    newrow.add(ny);
                }else {
                    publisher = splitfourkinds[3].trim();
                    if (publisher.contains("时间")){
                        publisher = publisher.substring(0,publisher.length()-2);
                    }
                    newrow.add(publisher);
                }
            }
            //时间
            if (4 < j) {
                ny = splitfourkinds[4].trim();
                newrow.add(ny);
            }else {
                //第四段没有时间要判断第三段有没有时间,如果没有要补充完整
                if(!splitfourkinds[2].contains("时间")){
                    newrow.add(ny);
                }
            }
            newsheetlist.add(newrow);
        }catch (Exception e){
                //通过输出查看问题bug出在哪里了
                System.out.println("---当前循环第" + i +"次出现异常");
                System.out.println();
                e.printStackTrace();
                continue;
            }
        }
        return newsheetlist;
    }


    public static void main (String[] args) throws Exception {
//        Connection conn = new connesql();
//        System.out.println(import_sheet(newsheetlist(getResult()),conn));
        connesql.import_sheet(newsheetlist(getResult()));
        }

}


import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

public class connesql {
    public static Connection getconnection() {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/elct?characterEncoding=utf8&useUnicode=true&sessionVariables=storage_engine%3DInnoDB&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        String user = "root";
        String password = "123456";
        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2.连接数据库
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("连接成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

    public static void import_sheet(List<List<String>> newsheetlist) {
        Connection conn = getconnection();
        try {
            Statement sm = conn.createStatement();
            //取每个字段的值,存入数据库
            for (int i = 0; i < newsheetlist.size(); i++) {
                List<String> row = newsheetlist.get(i);
                String zflmc = row.get(0);
                String title = row.get(1);
                String author = row.get(2);
                String cbs = row.get(3);
                String ny = row.get(4);

                String sql = "insert into dc_acticle (flid,zflmc,title,author,cbs,ny) " +
                        "values(8,"
                        +"'"+zflmc+"'"+","
                        +"'"+title+"'"+","
                        +"'"+author+"'"+","
                        +"'"+cbs+"'"+","
                        +"'"+ny+"'"+
                        ")";
                System.out.println(sql);
                sm.executeUpdate(sql);
            }
            sm.close();
            conn.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}



阅读更多
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭