zoukankan      html  css  js  c++  java
  • 使用JDBC+POI把Excel中的数据导出到MySQL

    POI是Apache的一套读MS文档的API,用它还是可以比较方便的读取Office文档的。目前支持Word,Excel,PowerPoint生成的文档,还有Visio和Publisher的。

    http://poi.apache.org/download.html

    具体的用法可以查阅文档里面您的quickguide,我给出我自己的范例,从xls文件把数据导出到MySQL

    这里面我总是假定excel在第一个sheet并且第一行是字段名,能够自动从第一行读取字段名建立一个表然后导入数据。

    1. package JDBCPractice;  
    2. import java.io.*;  
    3. import java.sql.*;  
    4. import org.apache.poi.hssf.*;  
    5. import org.apache.poi.ss.usermodel.*;  
    6. import org.apache.poi.hssf.usermodel.HSSFCell;  
    7. import org.apache.poi.hssf.usermodel.HSSFRow;  
    8. import org.apache.poi.hssf.usermodel.HSSFSheet;  
    9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    10. // 导入hssf来处理xls文件  
    11. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
    12. // 使用poifs来读文件更加的轻松,当然也可以不用  
    13. public class main {  
    14.     /** 
    15.      * @param args 
    16.      */  
    17.     public static void main(String[] args) {  
    18.           
    19.         String addr = "/home/ulysess/Developer/T_user.XLS";  
    20.           
    21.         HSSFWorkbook wb = null;  
    22.         HSSFSheet contents = null;  
    23.           
    24.         try {  
    25.             POIFSFileSystem exlf = new POIFSFileSystem(new FileInputStream(addr));  
    26.             wb = new HSSFWorkbook(exlf);  
    27.         } catch (FileNotFoundException e) {  
    28.             System.out.println("文件不存在,请检查路径");  
    29.             e.printStackTrace();  
    30.             return;  
    31.         } catch (IOException e) {  
    32.             System.out.println("读取文件时发生IO错误");  
    33.             e.printStackTrace();  
    34.             return;  
    35.         }  
    36.         contents = wb.getSheetAt(0);  
    37.         //取第一个sheet  
    38.         int minColIdx, maxColIdx, maxRowIdx;  
    39.         maxRowIdx = contents.getLastRowNum();  
    40.         HSSFRow xlrow = contents.getRow(0);  
    41.         //-----------------------建立MySQL连接-------------------------  
    42.         try {  
    43.             Class.forName("com.mysql.jdbc.Driver");  
    44.             //建立一个mysql的driver的实例,并将其注册到DriversManager  
    45.         } catch (ClassNotFoundException e) {  
    46.             System.out.println("Unable load Driver");  
    47.             e.printStackTrace();  
    48.         }  
    49.           
    50.         String name = "root";  
    51.         String password = "moratorium";  
    52.         String url = "jdbc:mysql://localhost/USERDATAS";  
    53.         try {  
    54.             Connection con = DriverManager.getConnection(url, name, password);  
    55.             //建立连接  
    56.               
    57.             Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,    
    58.                      ResultSet.CONCUR_UPDATABLE);    
    59.               
    60.             try {  
    61.                 /*stmt.execute("create table ORGDATAS( " + 
    62.                     "USERID VARCHAR(24) NOT NULL PRIMARY KEY," + 
    63.                     " USERNAME VARCHAR(24), SEX TINYINT, " + 
    64.                     "PASSWORD VARCHAR(64), USERTYPE TINYINT, " + 
    65.                     "FREEAUTHEN TINYINT, CERTIFICATETYPE TINYINT, " + 
    66.                     "CERTIFICATENO VARCHAR(24), EDUCATION TINYINT, " + 
    67.                     "POSTCODE VARCHAR(10), ADDRESS VARCHAR(128), " + 
    68.                     "PHONENO VARCHAR(24), BIRTHDAY DATE, EMAIL VARCHAR(64) );");*/  
    69.                 //建表  
    70.                 HSSFCell cel, refcell;  
    71.                 HSSFRow ferr = contents.getRow(1);  
    72.                 String ctbsql = "create table TARGETTABLE (";  
    73.                 for(int i = xlrow.getFirstCellNum(); i < xlrow.getLastCellNum(); i++) {  
    74.                     cel = xlrow.getCell(i);  
    75.                     refcell = ferr.getCell(i);  
    76.                     if(refcell == null) {  
    77.                         ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    78.                     } else {  
    79.                         switch(refcell.getCellType()) {  
    80.                         case Cell.CELL_TYPE_FORMULA:  
    81.                         case Cell.CELL_TYPE_STRING:  
    82.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    83.                             break;  
    84.                         case Cell.CELL_TYPE_NUMERIC:  
    85.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " INT");  
    86.                             break;  
    87.                         case Cell.CELL_TYPE_BOOLEAN:  
    88.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " TINYINT");  
    89.                             break;  
    90.                         default:  
    91.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    92.                         }  
    93.                     }  
    94.                     if(i < xlrow.getLastCellNum()-1) {  
    95.                         if(i == 0 ) {  
    96.                             ctbsql = ctbsql.concat(" NOT NULL PRIMARY KEY");  
    97.                         }  
    98.                         ctbsql = ctbsql.concat(", ");  
    99.                     }else {  
    100.                         ctbsql = ctbsql.concat(");");  
    101.                     }  
    102.                 }  
    103.                 stmt.execute(ctbsql);  
    104.                 //跟据前两行的内容来建表  
    105.                   
    106.             } catch(SQLException e) {  
    107.             }  
    108.               
    109.             ResultSet rs = stmt.executeQuery("select * from TARGETTABLE");  
    110.               
    111.               
    112.             minColIdx = xlrow.getFirstCellNum();  
    113.             maxColIdx = xlrow.getLastCellNum();  
    114.             //设定每列的最小最大索引  
    115.             int cnt =0 ;  
    116.             boolean infirstrow = true;  
    117.             //for each式遍历整个表  
    118.             for (Row row : contents) {  
    119.                 if(infirstrow) {  
    120.                     infirstrow = false;  
    121.                     continue;  
    122.                 }  
    123.                 rs.moveToInsertRow();  
    124.                 System.out.println("insert " + cnt++);  
    125.                 for (Cell cell : row) {  
    126.                     if(cell == null) {  
    127.                         continue;  
    128.                     }  
    129.                     switch(cell.getCellType()) {  
    130.                     case Cell.CELL_TYPE_FORMULA:  
    131.                     case Cell.CELL_TYPE_STRING:  
    132.                         rs.updateString(cell.getColumnIndex() + 1, cell.getStringCellValue());  
    133.                         break;  
    134.                     case Cell.CELL_TYPE_NUMERIC:  
    135.                         rs.updateInt(cell.getColumnIndex() + 1, (int) cell.getNumericCellValue());  
    136.                         break;  
    137.                     case Cell.CELL_TYPE_BOOLEAN:  
    138.                         rs.updateShort(cell.getColumnIndex() + 1, (short) cell.getNumericCellValue());  
    139.                         break;  
    140.                     default:  
    141.                         rs.updateString(cell.getColumnIndex() + 1, cell.getStringCellValue());  
    142.                     }  
    143.                 }  
    144.                 rs.insertRow();  
    145.             }  
    146.               
    147.             System.out.println("--------------------------");  
    148.               
    149.         } catch (SQLException e) {  
    150.             e.printStackTrace();  
    151.             System.out.println("/n--- SQLException caught ---/n");  
    152.             while (e != null) {  
    153.                 System.out.println("Message:   "  
    154.                                            + e.getMessage ());  
    155.                 System.out.println("SQLState:  "  
    156.                                            + e.getSQLState ());  
    157.                 System.out.println("ErrorCode: "  
    158.                                            + e.getErrorCode ());  
    159.                 e = e.getNextException();  
    160.                 e.printStackTrace();  
    161.                 System.out.println("");  
    162.             }  
    163.         } catch (IllegalStateException ie) {  
    164.             ie.printStackTrace();  
    165.         }  
    166.           
    167.           
    168.           
    169.     }  
    170. }  
     
     
    另一篇提到:
     

    在项目中用户需要导入大量Excel表格数据到数据库,为此需求自己写了一个读取Excel数据的Java类,现将代码贴出来与大家一起分享。

    该类提供两个方法,一个方法用于读取Excel表格的表头,另一个方法用于读取Excel表格的内容。

    (注:本类需要POI组件的支持,POI是apache组织下的一个开源组件,)

    代码如下:

    Java代码 复制代码
    1. package org.hnylj.poi.util;   
    2.   
    3. import java.io.FileInputStream;   
    4. import java.io.FileNotFoundException;   
    5. import java.io.IOException;   
    6. import java.io.InputStream;   
    7. import java.util.Date;   
    8. import java.util.HashMap;   
    9. import java.util.Map;   
    10.   
    11. import org.apache.poi.hssf.usermodel.HSSFCell;   
    12. import org.apache.poi.hssf.usermodel.HSSFRow;   
    13. import org.apache.poi.hssf.usermodel.HSSFSheet;   
    14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
    15. import org.apache.poi.poifs.filesystem.POIFSFileSystem;   
    16.   
    17. /**  
    18.  * 操作Excel表格的功能类  
    19.  * @author:hnylj  
    20.  * @version 1.0  
    21.  */  
    22. public class ExcelReader {   
    23.     private POIFSFileSystem fs;   
    24.     private HSSFWorkbook wb;   
    25.     private HSSFSheet sheet;   
    26.     private HSSFRow row;   
    27.     /**  
    28.      * 读取Excel表格表头的内容  
    29.      * @param InputStream  
    30.      * @return String 表头内容的数组  
    31.      *   
    32.      */  
    33.     public String[] readExcelTitle(InputStream is) {   
    34.         try {   
    35.             fs = new POIFSFileSystem(is);   
    36.             wb = new HSSFWorkbook(fs);   
    37.         } catch (IOException e) {   
    38.             e.printStackTrace();   
    39.         }   
    40.         sheet = wb.getSheetAt(0);   
    41.         row = sheet.getRow(0);   
    42.         //标题总列数   
    43.         int colNum = row.getPhysicalNumberOfCells();   
    44.         String[] title = new String[colNum];   
    45.         for (int i=0; i<colNum; i++) {   
    46.             title[i] = getStringCellValue(row.getCell((short) i));   
    47.         }   
    48.         return title;   
    49.     }   
    50.        
    51.     /**  
    52.      * 读取Excel数据内容  
    53.      * @param InputStream  
    54.      * @return Map 包含单元格数据内容的Map对象  
    55.      */  
    56.     public Map<Integer,String> readExcelContent(InputStream is) {   
    57.         Map<Integer,String> content = new HashMap<Integer,String>();   
    58.         String str = "";   
    59.         try {   
    60.             fs = new POIFSFileSystem(is);   
    61.             wb = new HSSFWorkbook(fs);   
    62.         } catch (IOException e) {   
    63.             e.printStackTrace();   
    64.         }   
    65.         sheet = wb.getSheetAt(0);   
    66.         //得到总行数   
    67.         int rowNum = sheet.getLastRowNum();   
    68.         row = sheet.getRow(0);   
    69.         int colNum = row.getPhysicalNumberOfCells();   
    70.         //正文内容应该从第二行开始,第一行为表头的标题   
    71.         for (int i = 1; i <= rowNum; i++) {   
    72.             row = sheet.getRow(i);   
    73.             int j = 0;   
    74.             while (j<colNum) {   
    75.         //每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据   
    76.         //也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean   
    77.                 str += getStringCellValue(row.getCell((short) j)).trim() + "-";   
    78.                 j ++;   
    79.             }   
    80.             content.put(i, str);   
    81.             str = "";   
    82.         }   
    83.         return content;   
    84.     }   
    85.        
    86.     /**  
    87.      * 获取单元格数据内容为字符串类型的数据  
    88.      * @param cell Excel单元格  
    89.      * @return String 单元格数据内容  
    90.      */  
    91.     private String getStringCellValue(HSSFCell cell) {   
    92.         String strCell = "";   
    93.         switch (cell.getCellType()) {   
    94.         case HSSFCell.CELL_TYPE_STRING:   
    95.             strCell = cell.getStringCellValue();   
    96.             break;   
    97.         case HSSFCell.CELL_TYPE_NUMERIC:   
    98.             strCell = String.valueOf(cell.getNumericCellValue());   
    99.             break;   
    100.         case HSSFCell.CELL_TYPE_BOOLEAN:   
    101.             strCell = String.valueOf(cell.getBooleanCellValue());   
    102.             break;   
    103.         case HSSFCell.CELL_TYPE_BLANK:   
    104.             strCell = "";   
    105.             break;   
    106.         default:   
    107.             strCell = "";   
    108.             break;   
    109.         }   
    110.         if (strCell.equals("") || strCell == null) {   
    111.             return "";   
    112.         }   
    113.         if (cell == null) {   
    114.             return "";   
    115.         }   
    116.         return strCell;   
    117.     }   
    118.        
    119.     /**  
    120.      * 获取单元格数据内容为日期类型的数据  
    121.      * @param cell Excel单元格  
    122.      * @return String 单元格数据内容  
    123.      */  
    124.     private String getDateCellValue(HSSFCell cell) {   
    125.         String result = "";   
    126.         try {   
    127.             int cellType = cell.getCellType();   
    128.             if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {   
    129.                 Date date = cell.getDateCellValue();   
    130.                 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)    
    131.                 + "-" + date.getDate();   
    132.             } else if (cellType == HSSFCell.CELL_TYPE_STRING) {   
    133.                 String date = getStringCellValue(cell);   
    134.                 result = date.replaceAll("[年月]""-").replace("日""").trim();   
    135.             } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {   
    136.                 result = "";   
    137.             }   
    138.         } catch (Exception e) {   
    139.             System.out.println("日期格式不正确!");   
    140.             e.printStackTrace();   
    141.         }   
    142.         return result;   
    143.     }   
    144.        
    145.     public static void main(String[] args) {   
    146.         try {   
    147.             //对读取Excel表格标题测试   
    148.             InputStream is = new FileInputStream("C:\Excel表格测试.xls");   
    149.             ExcelReader excelReader = new ExcelReader();   
    150.             String[] title = excelReader.readExcelTitle(is);   
    151.             System.out.println("获得Excel表格的标题:");   
    152.             for (String s : title) {   
    153.                 System.out.print(s + " ");   
    154.             }   
    155.                
    156.             //对读取Excel表格内容测试   
    157.             InputStream is2 = new FileInputStream("C:\Excel表格测试.xls");   
    158.             Map<Integer,String> map = excelReader.readExcelContent(is2);   
    159.             System.out.println("获得Excel表格的内容:");   
    160.             for (int i=1; i<=map.size(); i++) {   
    161.                 System.out.println(map.get(i));   
    162.             }   
    163.         } catch (FileNotFoundException e) {   
    164.             System.out.println("未找到指定路径的文件!");   
    165.             e.printStackTrace();   
    166.         }   
    167.     }   
    168. }  
    Java代码  收藏代码
    1. package org.hnylj.poi.util;  
    2.   
    3. import java.io.FileInputStream;  
    4. import java.io.FileNotFoundException;  
    5. import java.io.IOException;  
    6. import java.io.InputStream;  
    7. import java.util.Date;  
    8. import java.util.HashMap;  
    9. import java.util.Map;  
    10.   
    11. import org.apache.poi.hssf.usermodel.HSSFCell;  
    12. import org.apache.poi.hssf.usermodel.HSSFRow;  
    13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
    14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    15. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
    16.   
    17. /** 
    18.  * 操作Excel表格的功能类 
    19.  * @author:hnylj 
    20.  * @version 1.0 
    21.  */  
    22. public class ExcelReader {  
    23.     private POIFSFileSystem fs;  
    24.     private HSSFWorkbook wb;  
    25.     private HSSFSheet sheet;  
    26.     private HSSFRow row;  
    27.     /** 
    28.      * 读取Excel表格表头的内容 
    29.      * @param InputStream 
    30.      * @return String 表头内容的数组 
    31.      *  
    32.      */  
    33.     public String[] readExcelTitle(InputStream is) {  
    34.         try {  
    35.             fs = new POIFSFileSystem(is);  
    36.             wb = new HSSFWorkbook(fs);  
    37.         } catch (IOException e) {  
    38.             e.printStackTrace();  
    39.         }  
    40.         sheet = wb.getSheetAt(0);  
    41.         row = sheet.getRow(0);  
    42.         //标题总列数  
    43.         int colNum = row.getPhysicalNumberOfCells();  
    44.         String[] title = new String[colNum];  
    45.         for (int i=0; i<colNum; i++) {  
    46.             title[i] = getStringCellValue(row.getCell((short) i));  
    47.         }  
    48.         return title;  
    49.     }  
    50.       
    51.     /** 
    52.      * 读取Excel数据内容 
    53.      * @param InputStream 
    54.      * @return Map 包含单元格数据内容的Map对象 
    55.      */  
    56.     public Map<Integer,String> readExcelContent(InputStream is) {  
    57.         Map<Integer,String> content = new HashMap<Integer,String>();  
    58.         String str = "";  
    59.         try {  
    60.             fs = new POIFSFileSystem(is);  
    61.             wb = new HSSFWorkbook(fs);  
    62.         } catch (IOException e) {  
    63.             e.printStackTrace();  
    64.         }  
    65.         sheet = wb.getSheetAt(0);  
    66.         //得到总行数  
    67.         int rowNum = sheet.getLastRowNum();  
    68.         row = sheet.getRow(0);  
    69.         int colNum = row.getPhysicalNumberOfCells();  
    70.         //正文内容应该从第二行开始,第一行为表头的标题  
    71.         for (int i = 1; i <= rowNum; i++) {  
    72.             row = sheet.getRow(i);  
    73.             int j = 0;  
    74.             while (j<colNum) {  
    75.         //每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据  
    76.         //也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean  
    77.                 str += getStringCellValue(row.getCell((short) j)).trim() + "-";  
    78.                 j ++;  
    79.             }  
    80.             content.put(i, str);  
    81.             str = "";  
    82.         }  
    83.         return content;  
    84.     }  
    85.       
    86.     /** 
    87.      * 获取单元格数据内容为字符串类型的数据 
    88.      * @param cell Excel单元格 
    89.      * @return String 单元格数据内容 
    90.      */  
    91.     private String getStringCellValue(HSSFCell cell) {  
    92.         String strCell = "";  
    93.         switch (cell.getCellType()) {  
    94.         case HSSFCell.CELL_TYPE_STRING:  
    95.             strCell = cell.getStringCellValue();  
    96.             break;  
    97.         case HSSFCell.CELL_TYPE_NUMERIC:  
    98.             strCell = String.valueOf(cell.getNumericCellValue());  
    99.             break;  
    100.         case HSSFCell.CELL_TYPE_BOOLEAN:  
    101.             strCell = String.valueOf(cell.getBooleanCellValue());  
    102.             break;  
    103.         case HSSFCell.CELL_TYPE_BLANK:  
    104.             strCell = "";  
    105.             break;  
    106.         default:  
    107.             strCell = "";  
    108.             break;  
    109.         }  
    110.         if (strCell.equals("") || strCell == null) {  
    111.             return "";  
    112.         }  
    113.         if (cell == null) {  
    114.             return "";  
    115.         }  
    116.         return strCell;  
    117.     }  
    118.       
    119.     /** 
    120.      * 获取单元格数据内容为日期类型的数据 
    121.      * @param cell Excel单元格 
    122.      * @return String 单元格数据内容 
    123.      */  
    124.     private String getDateCellValue(HSSFCell cell) {  
    125.         String result = "";  
    126.         try {  
    127.             int cellType = cell.getCellType();  
    128.             if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {  
    129.                 Date date = cell.getDateCellValue();  
    130.                 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)   
    131.                 + "-" + date.getDate();  
    132.             } else if (cellType == HSSFCell.CELL_TYPE_STRING) {  
    133.                 String date = getStringCellValue(cell);  
    134.                 result = date.replaceAll("[年月]""-").replace("日""").trim();  
    135.             } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {  
    136.                 result = "";  
    137.             }  
    138.         } catch (Exception e) {  
    139.             System.out.println("日期格式不正确!");  
    140.             e.printStackTrace();  
    141.         }  
    142.         return result;  
    143.     }  
    144.       
    145.     public static void main(String[] args) {  
    146.         try {  
    147.             //对读取Excel表格标题测试  
    148.             InputStream is = new FileInputStream("C:\Excel表格测试.xls");  
    149.             ExcelReader excelReader = new ExcelReader();  
    150.             String[] title = excelReader.readExcelTitle(is);  
    151.             System.out.println("获得Excel表格的标题:");  
    152.             for (String s : title) {  
    153.                 System.out.print(s + " ");  
    154.             }  
    155.               
    156.             //对读取Excel表格内容测试  
    157.             InputStream is2 = new FileInputStream("C:\Excel表格测试.xls");  
    158.             Map<Integer,String> map = excelReader.readExcelContent(is2);  
    159.             System.out.println("获得Excel表格的内容:");  
    160.             for (int i=1; i<=map.size(); i++) {  
    161.                 System.out.println(map.get(i));  
    162.             }  
    163.         } catch (FileNotFoundException e) {  
    164.             System.out.println("未找到指定路径的文件!");  
    165.             e.printStackTrace();  
    166.         }  
    167.     }  
    168. }  

    通过该类提供的方法就能读取出Excel表格中的数据,数据读取出来了,其他的,对这些数据进行怎样的操作,要靠你另外写程序去实现,因为该类只提供读取Excel表格数据的功能。

     

    说明:在该类中有一个getStringCellValue(HSSFCell cell)方法和一个getDateCellValue(HSSFCell cell)方法,前一个方法用于读取那些为字符串类型的数据,如果你的Excel表格中填写的是日期类型的数据,则你应该在readExcelContent(InputStream is)方法里调用getDateCellValue(HSSFCell cell)方法,因为若调用getStringCellValue(HSSFCell cell)方法读取日期类型的数据将得到的是一个浮点数,这很可能不符合实际要求。

    1. package JDBCPractice;  
    2. import java.io.*;  
    3. import java.sql.*;  
    4. import org.apache.poi.hssf.*;  
    5. import org.apache.poi.ss.usermodel.*;  
    6. import org.apache.poi.hssf.usermodel.HSSFCell;  
    7. import org.apache.poi.hssf.usermodel.HSSFRow;  
    8. import org.apache.poi.hssf.usermodel.HSSFSheet;  
    9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    10. // 导入hssf来处理xls文件  
    11. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
    12. // 使用poifs来读文件更加的轻松,当然也可以不用  
    13. public class main {  
    14.     /** 
    15.      * @param args 
    16.      */  
    17.     public static void main(String[] args) {  
    18.           
    19.         String addr = "/home/ulysess/Developer/T_user.XLS";  
    20.           
    21.         HSSFWorkbook wb = null;  
    22.         HSSFSheet contents = null;  
    23.           
    24.         try {  
    25.             POIFSFileSystem exlf = new POIFSFileSystem(new FileInputStream(addr));  
    26.             wb = new HSSFWorkbook(exlf);  
    27.         } catch (FileNotFoundException e) {  
    28.             System.out.println("文件不存在,请检查路径");  
    29.             e.printStackTrace();  
    30.             return;  
    31.         } catch (IOException e) {  
    32.             System.out.println("读取文件时发生IO错误");  
    33.             e.printStackTrace();  
    34.             return;  
    35.         }  
    36.         contents = wb.getSheetAt(0);  
    37.         //取第一个sheet  
    38.         int minColIdx, maxColIdx, maxRowIdx;  
    39.         maxRowIdx = contents.getLastRowNum();  
    40.         HSSFRow xlrow = contents.getRow(0);  
    41.         //-----------------------建立MySQL连接-------------------------  
    42.         try {  
    43.             Class.forName("com.mysql.jdbc.Driver");  
    44.             //建立一个mysql的driver的实例,并将其注册到DriversManager  
    45.         } catch (ClassNotFoundException e) {  
    46.             System.out.println("Unable load Driver");  
    47.             e.printStackTrace();  
    48.         }  
    49.           
    50.         String name = "root";  
    51.         String password = "moratorium";  
    52.         String url = "jdbc:mysql://localhost/USERDATAS";  
    53.         try {  
    54.             Connection con = DriverManager.getConnection(url, name, password);  
    55.             //建立连接  
    56.               
    57.             Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,    
    58.                      ResultSet.CONCUR_UPDATABLE);    
    59.               
    60.             try {  
    61.                 /*stmt.execute("create table ORGDATAS( " + 
    62.                     "USERID VARCHAR(24) NOT NULL PRIMARY KEY," + 
    63.                     " USERNAME VARCHAR(24), SEX TINYINT, " + 
    64.                     "PASSWORD VARCHAR(64), USERTYPE TINYINT, " + 
    65.                     "FREEAUTHEN TINYINT, CERTIFICATETYPE TINYINT, " + 
    66.                     "CERTIFICATENO VARCHAR(24), EDUCATION TINYINT, " + 
    67.                     "POSTCODE VARCHAR(10), ADDRESS VARCHAR(128), " + 
    68.                     "PHONENO VARCHAR(24), BIRTHDAY DATE, EMAIL VARCHAR(64) );");*/  
    69.                 //建表  
    70.                 HSSFCell cel, refcell;  
    71.                 HSSFRow ferr = contents.getRow(1);  
    72.                 String ctbsql = "create table TARGETTABLE (";  
    73.                 for(int i = xlrow.getFirstCellNum(); i < xlrow.getLastCellNum(); i++) {  
    74.                     cel = xlrow.getCell(i);  
    75.                     refcell = ferr.getCell(i);  
    76.                     if(refcell == null) {  
    77.                         ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    78.                     } else {  
    79.                         switch(refcell.getCellType()) {  
    80.                         case Cell.CELL_TYPE_FORMULA:  
    81.                         case Cell.CELL_TYPE_STRING:  
    82.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    83.                             break;  
    84.                         case Cell.CELL_TYPE_NUMERIC:  
    85.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " INT");  
    86.                             break;  
    87.                         case Cell.CELL_TYPE_BOOLEAN:  
    88.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " TINYINT");  
    89.                             break;  
    90.                         default:  
    91.                             ctbsql = ctbsql.concat(cel.getStringCellValue() + " VARCHAR(64)");  
    92.                         }  
    93.                     }  
    94.                     if(i < xlrow.getLastCellNum()-1) {  
    95.                         if(i == 0 ) {  
    96.                             ctbsql = ctbsql.concat(" NOT NULL PRIMARY KEY");  
    97.                         }  
    98.                         ctbsql = ctbsql.concat(", ");  
    99.                     }else {  
    100.                         ctbsql = ctbsql.concat(");");  
    101.                     }  
    102.                 }  
    103.                 stmt.execute(ctbsql);  
    104.                 //跟据前两行的内容来建表  
    105.                   
    106.             } catch(SQLException e) {  
    107.             }  
    108.               
    109.             ResultSet rs = stmt.executeQuery("select * from TARGETTABLE");  
    110.               
    111.               
    112.             minColIdx = xlrow.getFirstCellNum();  
    113.             maxColIdx = xlrow.getLastCellNum();  
    114.             //设定每列的最小最大索引  
    115.             int cnt =0 ;  
    116.             boolean infirstrow = true;  
    117.             //for each式遍历整个表  
    118.             for (Row row : contents) {  
    119.                 if(infirstrow) {  
    120.                     infirstrow = false;  
    121.                     continue;  
    122.                 }  
    123.                 rs.moveToInsertRow();  
    124.                 System.out.println("insert " + cnt++);  
    125.                 for (Cell cell : row) {  
    126.                     if(cell == null) {  
    127.                         continue;  
    128.                     }  
    129.                     switch(cell.getCellType()) {  
    130.                     case Cell.CELL_TYPE_FORMULA:  
    131.                     case Cell.CELL_TYPE_STRING:  
    132.                         rs.updateString(cell.getColumnIndex() + 1, cell.getStringCellValue());  
    133.                         break;  
    134.                     case Cell.CELL_TYPE_NUMERIC:  
    135.                         rs.updateInt(cell.getColumnIndex() + 1, (int) cell.getNumericCellValue());  
    136.                         break;  
    137.                     case Cell.CELL_TYPE_BOOLEAN:  
    138.                         rs.updateShort(cell.getColumnIndex() + 1, (short) cell.getNumericCellValue());  
    139.                         break;  
    140.                     default:  
    141.                         rs.updateString(cell.getColumnIndex() + 1, cell.getStringCellValue());  
    142.                     }  
    143.                 }  
    144.                 rs.insertRow();  
    145.             }  
    146.               
    147.             System.out.println("--------------------------");  
    148.               
    149.         } catch (SQLException e) {  
    150.             e.printStackTrace();  
    151.             System.out.println("/n--- SQLException caught ---/n");  
    152.             while (e != null) {  
    153.                 System.out.println("Message:   "  
    154.                                            + e.getMessage ());  
    155.                 System.out.println("SQLState:  "  
    156.                                            + e.getSQLState ());  
    157.                 System.out.println("ErrorCode: "  
    158.                                            + e.getErrorCode ());  
    159.                 e = e.getNextException();  
    160.                 e.printStackTrace();  
    161.                 System.out.println("");  
    162.             }  
    163.         } catch (IllegalStateException ie) {  
    164.             ie.printStackTrace();  
    165.         }  
    166.           
    167.           
    168.           
    169.     }  
    170. }  
     
     
    另一篇提到:
     

    在项目中用户需要导入大量Excel表格数据到数据库,为此需求自己写了一个读取Excel数据的Java类,现将代码贴出来与大家一起分享。

    该类提供两个方法,一个方法用于读取Excel表格的表头,另一个方法用于读取Excel表格的内容。

    (注:本类需要POI组件的支持,POI是apache组织下的一个开源组件,)

    代码如下:

    Java代码 复制代码
    1. package org.hnylj.poi.util;   
    2.   
    3. import java.io.FileInputStream;   
    4. import java.io.FileNotFoundException;   
    5. import java.io.IOException;   
    6. import java.io.InputStream;   
    7. import java.util.Date;   
    8. import java.util.HashMap;   
    9. import java.util.Map;   
    10.   
    11. import org.apache.poi.hssf.usermodel.HSSFCell;   
    12. import org.apache.poi.hssf.usermodel.HSSFRow;   
    13. import org.apache.poi.hssf.usermodel.HSSFSheet;   
    14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
    15. import org.apache.poi.poifs.filesystem.POIFSFileSystem;   
    16.   
    17. /**  
    18.  * 操作Excel表格的功能类  
    19.  * @author:hnylj  
    20.  * @version 1.0  
    21.  */  
    22. public class ExcelReader {   
    23.     private POIFSFileSystem fs;   
    24.     private HSSFWorkbook wb;   
    25.     private HSSFSheet sheet;   
    26.     private HSSFRow row;   
    27.     /**  
    28.      * 读取Excel表格表头的内容  
    29.      * @param InputStream  
    30.      * @return String 表头内容的数组  
    31.      *   
    32.      */  
    33.     public String[] readExcelTitle(InputStream is) {   
    34.         try {   
    35.             fs = new POIFSFileSystem(is);   
    36.             wb = new HSSFWorkbook(fs);   
    37.         } catch (IOException e) {   
    38.             e.printStackTrace();   
    39.         }   
    40.         sheet = wb.getSheetAt(0);   
    41.         row = sheet.getRow(0);   
    42.         //标题总列数   
    43.         int colNum = row.getPhysicalNumberOfCells();   
    44.         String[] title = new String[colNum];   
    45.         for (int i=0; i<colNum; i++) {   
    46.             title[i] = getStringCellValue(row.getCell((short) i));   
    47.         }   
    48.         return title;   
    49.     }   
    50.        
    51.     /**  
    52.      * 读取Excel数据内容  
    53.      * @param InputStream  
    54.      * @return Map 包含单元格数据内容的Map对象  
    55.      */  
    56.     public Map<Integer,String> readExcelContent(InputStream is) {   
    57.         Map<Integer,String> content = new HashMap<Integer,String>();   
    58.         String str = "";   
    59.         try {   
    60.             fs = new POIFSFileSystem(is);   
    61.             wb = new HSSFWorkbook(fs);   
    62.         } catch (IOException e) {   
    63.             e.printStackTrace();   
    64.         }   
    65.         sheet = wb.getSheetAt(0);   
    66.         //得到总行数   
    67.         int rowNum = sheet.getLastRowNum();   
    68.         row = sheet.getRow(0);   
    69.         int colNum = row.getPhysicalNumberOfCells();   
    70.         //正文内容应该从第二行开始,第一行为表头的标题   
    71.         for (int i = 1; i <= rowNum; i++) {   
    72.             row = sheet.getRow(i);   
    73.             int j = 0;   
    74.             while (j<colNum) {   
    75.         //每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据   
    76.         //也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean   
    77.                 str += getStringCellValue(row.getCell((short) j)).trim() + "-";   
    78.                 j ++;   
    79.             }   
    80.             content.put(i, str);   
    81.             str = "";   
    82.         }   
    83.         return content;   
    84.     }   
    85.        
    86.     /**  
    87.      * 获取单元格数据内容为字符串类型的数据  
    88.      * @param cell Excel单元格  
    89.      * @return String 单元格数据内容  
    90.      */  
    91.     private String getStringCellValue(HSSFCell cell) {   
    92.         String strCell = "";   
    93.         switch (cell.getCellType()) {   
    94.         case HSSFCell.CELL_TYPE_STRING:   
    95.             strCell = cell.getStringCellValue();   
    96.             break;   
    97.         case HSSFCell.CELL_TYPE_NUMERIC:   
    98.             strCell = String.valueOf(cell.getNumericCellValue());   
    99.             break;   
    100.         case HSSFCell.CELL_TYPE_BOOLEAN:   
    101.             strCell = String.valueOf(cell.getBooleanCellValue());   
    102.             break;   
    103.         case HSSFCell.CELL_TYPE_BLANK:   
    104.             strCell = "";   
    105.             break;   
    106.         default:   
    107.             strCell = "";   
    108.             break;   
    109.         }   
    110.         if (strCell.equals("") || strCell == null) {   
    111.             return "";   
    112.         }   
    113.         if (cell == null) {   
    114.             return "";   
    115.         }   
    116.         return strCell;   
    117.     }   
    118.        
    119.     /**  
    120.      * 获取单元格数据内容为日期类型的数据  
    121.      * @param cell Excel单元格  
    122.      * @return String 单元格数据内容  
    123.      */  
    124.     private String getDateCellValue(HSSFCell cell) {   
    125.         String result = "";   
    126.         try {   
    127.             int cellType = cell.getCellType();   
    128.             if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {   
    129.                 Date date = cell.getDateCellValue();   
    130.                 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)    
    131.                 + "-" + date.getDate();   
    132.             } else if (cellType == HSSFCell.CELL_TYPE_STRING) {   
    133.                 String date = getStringCellValue(cell);   
    134.                 result = date.replaceAll("[年月]""-").replace("日""").trim();   
    135.             } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {   
    136.                 result = "";   
    137.             }   
    138.         } catch (Exception e) {   
    139.             System.out.println("日期格式不正确!");   
    140.             e.printStackTrace();   
    141.         }   
    142.         return result;   
    143.     }   
    144.        
    145.     public static void main(String[] args) {   
    146.         try {   
    147.             //对读取Excel表格标题测试   
    148.             InputStream is = new FileInputStream("C:\Excel表格测试.xls");   
    149.             ExcelReader excelReader = new ExcelReader();   
    150.             String[] title = excelReader.readExcelTitle(is);   
    151.             System.out.println("获得Excel表格的标题:");   
    152.             for (String s : title) {   
    153.                 System.out.print(s + " ");   
    154.             }   
    155.                
    156.             //对读取Excel表格内容测试   
    157.             InputStream is2 = new FileInputStream("C:\Excel表格测试.xls");   
    158.             Map<Integer,String> map = excelReader.readExcelContent(is2);   
    159.             System.out.println("获得Excel表格的内容:");   
    160.             for (int i=1; i<=map.size(); i++) {   
    161.                 System.out.println(map.get(i));   
    162.             }   
    163.         } catch (FileNotFoundException e) {   
    164.             System.out.println("未找到指定路径的文件!");   
    165.             e.printStackTrace();   
    166.         }   
    167.     }   
    168. }  
    Java代码  收藏代码
    1. package org.hnylj.poi.util;  
    2.   
    3. import java.io.FileInputStream;  
    4. import java.io.FileNotFoundException;  
    5. import java.io.IOException;  
    6. import java.io.InputStream;  
    7. import java.util.Date;  
    8. import java.util.HashMap;  
    9. import java.util.Map;  
    10.   
    11. import org.apache.poi.hssf.usermodel.HSSFCell;  
    12. import org.apache.poi.hssf.usermodel.HSSFRow;  
    13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
    14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    15. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
    16.   
    17. /** 
    18.  * 操作Excel表格的功能类 
    19.  * @author:hnylj 
    20.  * @version 1.0 
    21.  */  
    22. public class ExcelReader {  
    23.     private POIFSFileSystem fs;  
    24.     private HSSFWorkbook wb;  
    25.     private HSSFSheet sheet;  
    26.     private HSSFRow row;  
    27.     /** 
    28.      * 读取Excel表格表头的内容 
    29.      * @param InputStream 
    30.      * @return String 表头内容的数组 
    31.      *  
    32.      */  
    33.     public String[] readExcelTitle(InputStream is) {  
    34.         try {  
    35.             fs = new POIFSFileSystem(is);  
    36.             wb = new HSSFWorkbook(fs);  
    37.         } catch (IOException e) {  
    38.             e.printStackTrace();  
    39.         }  
    40.         sheet = wb.getSheetAt(0);  
    41.         row = sheet.getRow(0);  
    42.         //标题总列数  
    43.         int colNum = row.getPhysicalNumberOfCells();  
    44.         String[] title = new String[colNum];  
    45.         for (int i=0; i<colNum; i++) {  
    46.             title[i] = getStringCellValue(row.getCell((short) i));  
    47.         }  
    48.         return title;  
    49.     }  
    50.       
    51.     /** 
    52.      * 读取Excel数据内容 
    53.      * @param InputStream 
    54.      * @return Map 包含单元格数据内容的Map对象 
    55.      */  
    56.     public Map<Integer,String> readExcelContent(InputStream is) {  
    57.         Map<Integer,String> content = new HashMap<Integer,String>();  
    58.         String str = "";  
    59.         try {  
    60.             fs = new POIFSFileSystem(is);  
    61.             wb = new HSSFWorkbook(fs);  
    62.         } catch (IOException e) {  
    63.             e.printStackTrace();  
    64.         }  
    65.         sheet = wb.getSheetAt(0);  
    66.         //得到总行数  
    67.         int rowNum = sheet.getLastRowNum();  
    68.         row = sheet.getRow(0);  
    69.         int colNum = row.getPhysicalNumberOfCells();  
    70.         //正文内容应该从第二行开始,第一行为表头的标题  
    71.         for (int i = 1; i <= rowNum; i++) {  
    72.             row = sheet.getRow(i);  
    73.             int j = 0;  
    74.             while (j<colNum) {  
    75.         //每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据  
    76.         //也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean  
    77.                 str += getStringCellValue(row.getCell((short) j)).trim() + "-";  
    78.                 j ++;  
    79.             }  
    80.             content.put(i, str);  
    81.             str = "";  
    82.         }  
    83.         return content;  
    84.     }  
    85.       
    86.     /** 
    87.      * 获取单元格数据内容为字符串类型的数据 
    88.      * @param cell Excel单元格 
    89.      * @return String 单元格数据内容 
    90.      */  
    91.     private String getStringCellValue(HSSFCell cell) {  
    92.         String strCell = "";  
    93.         switch (cell.getCellType()) {  
    94.         case HSSFCell.CELL_TYPE_STRING:  
    95.             strCell = cell.getStringCellValue();  
    96.             break;  
    97.         case HSSFCell.CELL_TYPE_NUMERIC:  
    98.             strCell = String.valueOf(cell.getNumericCellValue());  
    99.             break;  
    100.         case HSSFCell.CELL_TYPE_BOOLEAN:  
    101.             strCell = String.valueOf(cell.getBooleanCellValue());  
    102.             break;  
    103.         case HSSFCell.CELL_TYPE_BLANK:  
    104.             strCell = "";  
    105.             break;  
    106.         default:  
    107.             strCell = "";  
    108.             break;  
    109.         }  
    110.         if (strCell.equals("") || strCell == null) {  
    111.             return "";  
    112.         }  
    113.         if (cell == null) {  
    114.             return "";  
    115.         }  
    116.         return strCell;  
    117.     }  
    118.       
    119.     /** 
    120.      * 获取单元格数据内容为日期类型的数据 
    121.      * @param cell Excel单元格 
    122.      * @return String 单元格数据内容 
    123.      */  
    124.     private String getDateCellValue(HSSFCell cell) {  
    125.         String result = "";  
    126.         try {  
    127.             int cellType = cell.getCellType();  
    128.             if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {  
    129.                 Date date = cell.getDateCellValue();  
    130.                 result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)   
    131.                 + "-" + date.getDate();  
    132.             } else if (cellType == HSSFCell.CELL_TYPE_STRING) {  
    133.                 String date = getStringCellValue(cell);  
    134.                 result = date.replaceAll("[年月]""-").replace("日""").trim();  
    135.             } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {  
    136.                 result = "";  
    137.             }  
    138.         } catch (Exception e) {  
    139.             System.out.println("日期格式不正确!");  
    140.             e.printStackTrace();  
    141.         }  
    142.         return result;  
    143.     }  
    144.       
    145.     public static void main(String[] args) {  
    146.         try {  
    147.             //对读取Excel表格标题测试  
    148.             InputStream is = new FileInputStream("C:\Excel表格测试.xls");  
    149.             ExcelReader excelReader = new ExcelReader();  
    150.             String[] title = excelReader.readExcelTitle(is);  
    151.             System.out.println("获得Excel表格的标题:");  
    152.             for (String s : title) {  
    153.                 System.out.print(s + " ");  
    154.             }  
    155.               
    156.             //对读取Excel表格内容测试  
    157.             InputStream is2 = new FileInputStream("C:\Excel表格测试.xls");  
    158.             Map<Integer,String> map = excelReader.readExcelContent(is2);  
    159.             System.out.println("获得Excel表格的内容:");  
    160.             for (int i=1; i<=map.size(); i++) {  
    161.                 System.out.println(map.get(i));  
    162.             }  
    163.         } catch (FileNotFoundException e) {  
    164.             System.out.println("未找到指定路径的文件!");  
    165.             e.printStackTrace();  
    166.         }  
    167.     }  
    168. }  

    通过该类提供的方法就能读取出Excel表格中的数据,数据读取出来了,其他的,对这些数据进行怎样的操作,要靠你另外写程序去实现,因为该类只提供读取Excel表格数据的功能。

     

    说明:在该类中有一个getStringCellValue(HSSFCell cell)方法和一个getDateCellValue(HSSFCell cell)方法,前一个方法用于读取那些为字符串类型的数据,如果你的Excel表格中填写的是日期类型的数据,则你应该在readExcelContent(InputStream is)方法里调用getDateCellValue(HSSFCell cell)方法,因为若调用getStringCellValue(HSSFCell cell)方法读取日期类型的数据将得到的是一个浮点数,这很可能不符合实际要求。

  • 相关阅读:
    在Dictionary使用foreach的注意
    [公告]新增项目交流区
    博客园Blog程序中又一个奇怪问题
    公告
    网络爬客光顾博客园
    爬网的影响
    致歉
    [业界新闻]中文IT百科Beta版于2006年7月10日正式上线
    公告
    疯狂的爬网
  • 原文地址:https://www.cnblogs.com/111testing/p/6280427.html
Copyright © 2011-2022 走看看