ExcelOutDB.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import java.io.FileInputStream;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import org.apache.poi.hssf.usermodel.HSSFCell;
  6. import org.apache.poi.hssf.usermodel.HSSFRow;
  7. import org.apache.poi.hssf.usermodel.HSSFSheet;
  8. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  9. public class ExcelOutDB {
  10. public static void main(String[] args) throws Exception {
  11. //文件流指向excel文件
  12. FileInputStream fin=new FileInputStream("C:\\Users\\ASUS\\Desktop\\stu.xls");
  13. try {
  14. HSSFWorkbook workbook = new HSSFWorkbook(fin);
  15. HSSFSheet sheet=workbook.getSheetAt(0); //得到工作表
  16. HSSFRow row=null; //对应excel的行
  17. HSSFCell cell=null; //对应excel的列
  18. int totalRow=sheet.getLastRowNum(); //得到excel的总记录条数
  19. String user="";
  20. String name="";
  21. String password="";
  22. String sex="";
  23. String national="";
  24. String telephone="";
  25. String age="";
  26. Connection con = null; //数据库连接
  27. DBConnection db = new DBConnection();
  28. con = db.getDB();
  29. String sql="insert into student(user,name,password,sex,national,telephone,age) values(?,?,?,?,?,?,?)";
  30. //利用循环把数据导入数据库中
  31. for(int i=1;i<=totalRow;i++){
  32. row=sheet.getRow(i);
  33. cell=row.getCell((short) 0);
  34. user=cell.getRichStringCellValue().toString();
  35. cell=row.getCell((short) 1);
  36. name=cell.getRichStringCellValue().toString();
  37. cell=row.getCell((short) 2);
  38. password=cell.getRichStringCellValue().toString();
  39. cell=row.getCell((short) 3);
  40. sex=cell.getRichStringCellValue().toString();
  41. cell=row.getCell((short) 4);
  42. national=cell.getRichStringCellValue().toString();
  43. cell=row.getCell((short) 5);
  44. telephone=cell.getRichStringCellValue().toString();
  45. cell=row.getCell((short) 6);
  46. PreparedStatement pst=con.prepareStatement(sql);
  47. pst.setString(1,user);
  48. pst.setString(2,name);
  49. pst.setString(3,password);
  50. pst.setString(4,sex);
  51. pst.setString(5,national);
  52. pst.setString(6,telephone);
  53. pst.setString(7,age);
  54. pst.execute();
  55. }
  56. System.out.println("导入成功");
  57. } catch (IOException e) {
  58. // TODO 自动生成的 catch 块
  59. e.printStackTrace();
  60. }
  61. }
  62. }