servlet读取excel中的数据并添加到sqlserver数据库
前台上传文件的jsp页面(部分):
<form action="importExcel" enctype="multipart/form-data" method="post">
选择文件: <input type="file" name="excelfilename"><br>
请选择年份:<input type="text" name="qwe" id="qwe" onClick="WdatePicker({dateFmt:'yyyy'})" /><br> <!--这里使用的是时间控件-->
<input type="submit" value="数据入库"/>
</form>
servlet的配置文件web.xml(部分):
<servlet>
<servlet-name>importExcel</servlet-name>
<servlet-class>com.ImportExcel</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>importExcel</servlet-name>
<url-pattern>/importExcel</url-pattern>
</servlet-mapping>
servlet的处理页面(部分):
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String zhi=null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
InputStream is = null;
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
is = item.getInputStream();
}else{
if(item.getFieldName().equals("qwe")){
zhi=item.getString("gb2312");
System.out.println(zhi);
}
}
}
Workbook workbook = Workbook.getWorkbook(is);
Sheet sheet = workbook.getSheet(0);
int rows=sheet.getColumns();
Cell ce00=((jxl.Sheet) sheet).getCell(1,14);
Cell ce01=((jxl.Sheet) sheet).getCell(2,14);
Cell ce02=((jxl.Sheet) sheet).getCell(3,14);
Cell ce03=((jxl.Sheet) sheet).getCell(4,14);
Cell ce04=((jxl.Sheet) sheet).getCell(5,14);
String cel00=ce00.getContents();
String cel01=ce01.getContents();
String cel02=ce02.getContents();
String cel03=ce03.getContents();
String cel04=ce04.getContents();
Connection conn=basedao.openCon(); //调用链接数据库的文件
PreparedStatement ps=conn.prepareStatement("insert into CD_BI_ZYLSTJB(heji,zzls,jzls,gzls,year) values(?,?,?,?,?)");
ps.setString(1,cel00);
ps.setString(2,cel01);
ps.setString(3,cel02);
ps.setString(4,cel03);
ps.setString(5,zhi);
ps.execute();
ps.close();
conn.close();
response.sendRedirect("/test/index.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}