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

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

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

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

代码如下:

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

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

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

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

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

代码如下:

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

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

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

使用JDBC+POI把Excel中的数据导出到MySQL的更多相关文章

  1. 使用Python将Excel中的数据导入到MySQL

    使用Python将Excel中的数据导入到MySQL 工具 Python 2.7 xlrd MySQLdb 安装 Python 对于不同的系统安装方式不同,Windows平台有exe安装包,Ubunt ...

  2. POI向Excel中写入数据及追加数据

    import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import ...

  3. 使用OpenXml把Excel中的数据导出到DataSet中

    public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </sum ...

  4. 用JDBC把Excel中的数据导入到Mysql数据库中

    步骤:0.在Mysql数据库中先建好table 1.从Excel表格读数据 2.用JDBC连接Mysql数据库 3.把读出的数据导入到Mysql数据库的相应表中 其中,步骤0的table我是先在Mys ...

  5. excel中的数据导出为properties和map的方法

    在做项目的过程中,经常需要处理excel数据,特别是和业务人员配合时,业务人员喜欢使用excel处理一些数据,然后交给我们技术人员进行程序处理.利用POI读取写入excel数据,是经常使用的一个情景. ...

  6. 2019-03-20 用SSIS把Excel中的数据导出来保存到SQLServer中

    Control Flow 1.配置 好 图形 2.去变量那 配置好 文件路径 和 存储过程 3.在SQL Server创建对应的存储过程,该存储过程的功能是每次导入是清空原有的数据 4.如果不懂的参考 ...

  7. Sqoop2 将hdfs中的数据导出到MySQL

    1.进入sqoop2终端: [root@master /]# sqoop2 2.为客户端配置服务器: sqoop:000> set server --host master --port 120 ...

  8. 《sqoop实现hdfs中的数据导出至mysql数据库》

    报错Access denied for user 'root'@'localhost' (using password: YES)  参考一  参考二 登陆mysql时,root密码的修改 参考帖子h ...

  9. Java利用POI导入导出Excel中的数据

         首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...

随机推荐

  1. 关于 ArrayList.toArray() 和 Arrays.asList().toArray()方法

    1.ArrayList.toArray() 理解    * 通过源码我们可以看到返回的是Object类型的数组,失去了原有的实际类型,虽然底层存储是具体类型的对象,这也正体现了文档中说的:该方法起到了 ...

  2. JavaScript 异步进化史

    前言 JS 中最基础的异步调用方式是 callback,它将回调函数 callback 传给异步 API,由浏览器或 Node 在异步完成后,通知 JS 引擎调用 callback.对于简单的异步操作 ...

  3. 解决jenkins下使用HTML Publisher插件后查看html报告显示不正常

    在jenkins后使用html publisher查看html报告时,发现显示不全,很多东西显示不了. 在查看官方文档后,这原来是安全问题所导致的. Jenkins安全默认是将以下功能都关闭了 1.j ...

  4. vmware下Ubuntu屏幕分辨率设置

    1.查看现有设备 xrandr -q 输出如下: Screen 0: minimum 1 x 1, current 800 x 600, maximum 8192 x 8192 Virtual1 co ...

  5. 有向连通图增加多少边构成强联通(hdu3836,poj1236)

    hdu3836 求出强分量后缩点处理得到分支图,对分支图的每个强连通分量统计出度和入度.需要的边数就是:统计 入度=0 的顶点数 和 出度=0 的顶点数,选择两者中较大的一个,才能确保一个强连通图. ...

  6. XCache 一种快速可靠的PHP操作码缓存

    1,错误报告开启 错误报告是在PHP中一个非常有用的功能,应同时在开发阶段启用. 这可以帮助我们确定我们的代码中的问题. 最常用的功能是“E_ALL”,这有助于我们发现所有的警告和严重错误. 必须指出 ...

  7. poj3417Network【LCA】【树形DP】

    Yixght is a manager of the company called SzqNetwork(SN). Now she's very worried because she has jus ...

  8. ios-CoreLocation定位服务

    一.简单说明 1.CLLocationManager CLLocationManager的常用操作和属性 开始用户定位- (void)startUpdatingLocation; 停止用户定位- (v ...

  9. 最大生成树——LCA

    今天说是要练习LCA结果找了道题看着题解打完了,如此惭愧,Lca还得好好理解啊,感觉在最大生成树上做有点异样,可能还是不是很理解吧,在noip前一定要再把这道题再a一遍,好题啊. 这是2013noip ...

  10. JAVA 的wait(), notify()与synchronized同步机制

    转自:http://blog.csdn.net/zyplus/article/details/6672775 在JAVA中,是没有类似于PV操作.进程互斥等相关的方法的.JAVA的进程同步是通过syn ...