java excel import database

Excel import database

Import jxl,junit packages

Below is the code
import com.mavenTest.bean.User;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/4/16.
 */ 
public  class EcxelToDb {

    @Test
    public void test(){

        File file = new File("book.xls" );
         try {
             // Get the table
             // Here pay attention to the file created by the excel table tool, otherwise an error will be reported 
            Workbook wb= Workbook.getWorkbook(file);
             // Get the workbook 
            Sheet sh= wb.getSheet(0 );
             // Number of rows 
            int c= sh.getColumns();
             // Number of columns 
            int r= sh.getRows();
            List<User> users=new ArrayList<User>();
            for (int i = 1; i < r; i++) {
               User user = new User();
                for (int j = 0; j < c; j++) {
                    if ((j + 1) % 2 == 0) {
                        user.setPassword(sh.getCell(j, i).getContents());
                    } else {
                        user.setName(sh.getCell(j, i).getContents());
                    }
                }
                user.setDate(new Date());
                users.add(user);
            }
            System.out.println(users);
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (BiffException e) {
            e.printStackTrace ();
        }
    }
}

 

Guess you like

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