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. win7系统自带分区工具,能分出逻辑分区

    先把硬盘里除了你装系统的主分区以外的分区全删除运行CMD输入 DISKPART然后输入list disk,找到你要分的盘,假如是要分第1个硬盘的就输入:select disk 0 这样就选择了第一个硬 ...

  2. Panel结构

    参考weui的Panel结构 核心:定位,补充:对容器设置font-size:0,消除img下多出的3px,防止居中出现偏差. <!DOCTYPE html> <html lang= ...

  3. LeetCode 37 Sudoku Solver(求解数独)

    题目链接: https://leetcode.com/problems/sudoku-solver/?tab=Description   Problem : 解决数独问题,给出一个二维数组,将这个数独 ...

  4. sencha touch 在线实战培训 第一期 第三节

    2014.1.2晚上8点开的课 讲课进度比较快,好多同学反应说有些跟不上了... 呃,本期的课程是需要有一定的基础的. 建议大家多看看http://www.cnblogs.com/mlzs/p/346 ...

  5. 跟bWAPP学WEB安全(PHP代码)--SQL注入的一些技巧

    背景 模拟环境还是 bWAPP,只不过这个bWAPP的SQL注入有点多,一一写意义不大,在这边就利用这个环境来尝试一些SQL注入的技巧.并研究下PHP的防御代码. 普通的bWAPPSQL注入的简单介绍 ...

  6. 让google.com不跳转到google.com.hk

    自从google的服务器搬离中国大陆后,大陆地区用户用google服务时会自动跳转到香港的http://google.com.hk,,有关键字过滤而且偶尔不是很稳定,这对我们的生活工作都造成了困扰. ...

  7. 一辈子只有1次成为BAT的机会,你如何把握?

    本文转自:http://www.fmi.com.cn/index.php?m=content&c=index&a=show&catid=9&id=614308 感谢作者 ...

  8. Coding 代码管理快速入门(转)

    当项目创建好了之后,我们该如何上传代码到 coding 上呢? Coding 网站使用“ Git 仓库”(类似 github )来管理代码. 其操作原理在于:利用 git 服务,将本地的项目目录下的文 ...

  9. github基本用法

    本人github账号:https://github.com/pingfanren,喜欢的朋友可以给我点星.   Git是目前最先进的分布式版本控制系统,作为一个程序员,我们需要掌握其用法. 一:下载G ...

  10. windows下的C++与cuda编译器位置

    在windows下最常见的C++编译器为visual studio自带的编译器cl.exe 通常其所在目录为: C:\Program Files (x86)\Microsoft Visual Stud ...