Javaweb----上传文件,excle表格录入数据库的表中

来源:互联网 发布:nginx 根据ip分发 编辑:程序博客网 时间:2024/06/05 15:13

上传文件,excle表格录入数据库的表中

一开始遥望数据库中录入测试数据,但由于要做考试系统,所以用到了一个东西,那就是能不能把表格里的东西录入到数据库中呢?经过仔细的研究,终于找到一种方式了。下面来讲解一下把。

首先呢,<input>标签中可以上传文件图片什么的,必须要用到这个。这里需要用到SpringMVC、excle录入数据库的包。需要导入一些jar包。先在数据库中建好一个空表。

新建的web项目,导入jar包。在src目录下新建一个包。有这么些类。

//这个是链接数据库的类

public class DBConnection {
private static Connection con = null;


// 驱动程序名
private static  String driverName = "com.mysql.jdbc.Driver";
// 数据库用户名
private static  String userName = "root";
// 密码
private static  String userPasswd = "ffffff";
// 数据库名
private static  String dbName = "test";
// 联结字符串
private static  String url = "jdbc:mysql://localhost/" + dbName + "?user="
+ userName + "&password=" + userPasswd
+ "&useUnicode=true&characterEncoding=gbk";


public static  Connection getConnection() {


try {
Class.forName(driverName);
con = DriverManager.getConnection(url);


} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}


public static  void closeConnection() {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

//这个是实体类,里面是数据库的列名
public class Excel {
private String pid;
private String name;
private String num;
private String www;
public Excel(String pid, String name, String num, String www) {
super();
this.pid = pid;
this.name = name;
this.num = num;
this.www = www;
}
public Excel(){}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getWww() {
return www;
}
public void setWww(String www) {
this.www = www;
}

}

//.xlsx文件用XSSFWorkbook   .xlx 用的HSSFWorkbook      对表格的读入

public class TestExcel {
//记录类的输出信息-
Log log=LogFactory.getLog(TestExcel.class);
//获取Excel文档的路径-
//.xlsx文件用XSSFWorkbook   .xlx 用的HSSFWorkbook
//public static String filepath="D://www.xlsx";
public static void start(String path){
//创建对excel工作簿的引用
XSSFWorkbook wookbook;
try {
wookbook = new XSSFWorkbook(new FileInputStream(path));
//在Execl文档中,第一张工作表的缺省索引是0
//XSSFSheet sheet=wookbook.getSheetAt(0);
XSSFSheet sheet=wookbook.getSheet("Sheet1");
//获取到Execl文件中的所有行数-
int rows=sheet.getPhysicalNumberOfRows();
//遍历行
for(int i=1;i<rows;i++){
//读取左上端单元格
XSSFRow row=sheet.getRow(i);
//行不能空
if(row!=null){
//获取到所有的列-
int cells=row.getPhysicalNumberOfCells();
String value="";
//遍历列-
for(int j=0;j<cells;j++){
//获取列的值
XSSFCell cell=row.getCell(j);
if(cell!=null){
switch(cell.getCellType()){
//这个类型是:公式
//Excel里面的“公式”,可以用cell.getNumericCellValue(); 来获得“结果”,也就是“公式”计算之后的结果 
case HSSFCell.CELL_TYPE_FORMULA:
break;
//这个类型是:数字
case HSSFCell.CELL_TYPE_NUMERIC:
value+=cell.getNumericCellValue()+",";
break;
case HSSFCell.CELL_TYPE_STRING:
value+=cell.getStringCellValue()+",";
break;
default:
value +=0;
}
}
}
//将数据插入到mysql数据库中
String[] val=value.split(",");
Excel entity=new Excel();
entity.setPid(val[0]);
entity.setName(val[1]);
entity.setNum(val[2]);
entity.setWww(val[3]);
TestMethod method=new TestMethod();
int a=method.add(entity);
if(a>0){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}


}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}

//插入到数据库表中的类

public int add(Excel te){

Connection con = DBConnection.getConnection();
PreparedStatement pstmt = null;
int count = 0;
String sql = " insert into excel(pid,name,num,www) values(?,?,?,?)";
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, te.getPid());
pstmt.setString(2, te.getName());
pstmt.setString(3, te.getNum());
pstmt.setString(4, te.getWww());
count = pstmt.executeUpdate();
/*
* if(count==0){ throw new DataAlreadyExistException(); }
*/
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBConnection.closeConnection();
}
return count;
}


}

//springmvc 的类

@Controller
public class HelloSpringMVC {

//上传Excel
@RequestMapping("file/upload")
public String upload(HttpSession session,
@RequestParam MultipartFile file)throws IllegalStateException,IOException{
if(!file.isEmpty()){
String location=session.getServletContext().getRealPath("upload");
String path=location+"/"+
System.currentTimeMillis()+file.getOriginalFilename();
System.out.println(path);
file.transferTo(new File(path));
TestExcel.start(path);
}

return "ok";
}
}

//index.jsp中的表单

<form action="file/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传excle"><br>
  
    </form>

ok.jsp中没有东西。

ApplicationContext.xml和web.xml文件中自己配制吧。

这里面有几个问题:

1.你自己建的excle表中第一行需要有列名,如果没有列名第一条会录不进去,在TestExcel 类中for(int i=1;i<rows;i++)这里i改成0,就可以了。

2.注意你的电脑中新建的excle表的保存后缀名,如果是.xlsx文件用XSSFWorkbook   .xlx 用的HSSFWorkbook,在TestExcel 类中有注释。


1 0