Java 将excel中的内容导入数据库中
ExcelReader类,用来从excel中读取数据的,网上版本的修改版。
package dataDML; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** * 操作Excel表格的功能类 * @author: * @version */ public class ExcelReader { private POIFSFileSystem fs; private HSSFWorkbook wb; private HSSFSheet sheet; private HSSFRow row; /** * 读取Excel表格表头的内容 * @param InputStream * @return String 表头内容的数组 * */ public String[] readExcelTitle(InputStream is) { try { fs = new POIFSFileSystem(is); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); } sheet = wb.getSheetAt(0); row = sheet.getRow(0); //标题总列数 int colNum = row.getPhysicalNumberOfCells(); String[] title = new String[colNum]; for (int i=0; i<colNum; i++) { title[i] = getTitleValue(row.getCell((short) i)); } return title; } /** * 获取单元格数据内容为字符串类型的数据 * @param cell Excel单元格 * @return String 单元格数据内容,若为字符串的要加单引号 */ public String getStringCellValue(HSSFCell cell) { String strCell = ""; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: strCell = "'" + cell.getStringCellValue() + "'"; break; case HSSFCell.CELL_TYPE_NUMERIC: strCell = String.valueOf(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_BOOLEAN: strCell = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: strCell = "''"; break; default: strCell = "''"; break; } if (strCell.equals("''") || strCell == null) { return ""; } if (cell == null) { return ""; } return strCell; } public String getTitleValue(HSSFCell cell) { String strCell = cell.getStringCellValue(); return strCell; } }
下面是利用这个类读取数据并存储到已有的数据表中,这里要注意的一点是,从excel中读取的日期数据,除非是以文本形式存储的,取得的数据都不是日期形式,而是数字,是该日期距离1900年1月日的天数,为了能够正确存储到数据库中,我对该数据所对应的字段名进行了判断,如果包含"date",也就是日期字段的数据,就对其进行转化。具体见下面代码:
package dataDML; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public class DataInsert { public static String driver = "com.mysql.jdbc.Driver"; public static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";//之所以链接地址后面会添加参数,是为了防止中文乱码 public static Connection conn; public static void main(String[] args) { try { Class.forName(driver); conn = DriverManager.getConnection(url,"test", "test123"); insertData("tbname");//tbname,为要插入的数据表名 } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void insertData(String tbName){ try { //casilin:插入数据,先从excel中读取数据 InputStream is = new FileInputStream("D://test.xls"); ExcelReader excelReader = new ExcelReader(); String[] colName = excelReader.readExcelTitle(is); //开始建立插入的sql语句,每一次插入的开头都是不变的,都是字段名 StringBuffer sqlBegin = new StringBuffer("insert into " + tbName + "("); //获取字段名,并添加入sql语句中 for (int i = 0; i < colName.length; i ++){ sqlBegin.append(colName[i]); if (i != colName.length -1) { sqlBegin.append(","); } } sqlBegin.append(") values("); is.close(); //下面读取字段内容 POIFSFileSystem fs; HSSFWorkbook wb; HSSFSheet sheet; HSSFRow row; is = new FileInputStream("D://casilin//testFiles//test.xls"); fs = new POIFSFileSystem(is); wb = new HSSFWorkbook(fs); sheet = wb.getSheetAt(0); //得到总行数 int rowNum = sheet.getLastRowNum(); row = sheet.getRow(0); int colNum = row.getPhysicalNumberOfCells(); //正文内容应该从第二行开始,第一行为表头的标题 String sql = new String(sqlBegin); String temp; for (int i = 1; i <= rowNum; i++) { row = sheet.getRow(i); int j = 0; while (j<colNum) { temp = excelReader.getStringCellValue(row.getCell((short) j)).trim(); //日期的特殊处理 if (colName[j].indexOf("date") != -1){ temp = temp.substring(0, temp.length()-2); //excel是以1990年为基数的,而java中的date是以1970年为基数的。所以要扣除差 25569天 Date d = new Date((Long.valueOf(temp) - 25569) * 24 * 3600 * 1000); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); temp = "'" + formater.format(d) + "'"; } sql = sql + temp; if (j != colNum-1){ sql = sql + ","; } j ++; } sql = sql + ")"; System.out.println(sql.toString()); PreparedStatement ps = conn.prepareStatement(sql.toString()); ps.execute(); ps.close(); sql = ""; sql = sqlBegin.toString(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
这里会用到一个Jar包:poi.jar,自己可以到网上搜一下,我就不提供地址了。