java 读取execl文件

java 中读取execl文件是必要功能,下面说下几种读取方式

1.jxl   (支持2003 不支持 2007  貌似最新版支持)

  1. /** 
  2.   * 规则设置的模板导入 
  3.   * @param file 
  4.   * @param exportDefindColum 
  5.   * @param exportDefindRemark 
  6.   * @param exportDefineid 
  7.   * @return 
  8.   * @throws Exception 
  9.   */ 
  10.  public List readSmProfitRuleExcel(File file,String[] defineColums,String[] defineRemarks,String[] defineids) throws Exception{ 
  11.   Workbook book = null; 
  12.   Cell cell = null; 
  13.   try { 
  14.    WorkbookSettings setting = new WorkbookSettings();    
  15.    java.util.Locale locale = new java.util.Locale("zh","CN");    
  16.    setting.setLocale(locale); 
  17.    setting.setEncoding("ISO-8859-1"); 
  18.    book = Workbook.getWorkbook(file, setting); 
  19.   } catch (Exception e2) { 
  20.    throw new Exception("Excel文件" + file.getName() + "读取出错。"); 
  21.   } 
  22.   List list = new ArrayList(); 
  23.   try { 
  24.    Sheet sheet = book.getSheet(0); 
  25.    int rows=sheet.getRows(); 
  26.    int columns=sheet.getColumns(); 
  27.    if(rows==0){ 
  28.     throw new Exception("Excel文件" + file.getName() + "无任何内容,禁止导入。"); 
  29.    } 
  30.    if(columns!=defineColums.length+1){ 
  31.     System.out.println("取出execl"+columns+"行,实际取出"+defineColums+1+"行"); 
  32.     throw new Exception("Excel文件" + file.getName() + "列头与模板列头不符 ,禁止导入 (如修改了规则,需存档重新生成模板再导入)。"); 
  33.    } 
  34.    for (int i = 0; i < defineids.length; i++) { 
  35.     String head = defineRemarks[i]+"-"+defineColums[i].substring(defineColums[i].indexOf(":")+1); 
  36.     if(!sheet.getCell(i,0).getContents().equals(head)){ 
  37.      System.out.println("取出execl列头"+sheet.getCell(i,0).getContents()+",实际取出"+head+"不匹配"); 
  38.      throw new Exception("Excel文件" + file.getName() + "列头与模板列头不符 ,禁止导入 (如修改了规则,需存档重新生成模板再导入)。"); 
  39.     } 
  40.    } 
  41.     
  42.    for (int i = 1; i < rows; i++) { 
  43.     for (int j = 0; j < columns; j++) { 
  44.      String content=sheet.getCell(j,i).getContents().trim(); 
  45.      if(content.equals("")){ 
  46.       throw new Exception("Excel文件" + file.getName() + "第"+(i+1)+"行,第"+(j+1)+"列存在空数据,禁止导入"); 
  47.      } 
  48.      Map<String, String> map = new HashMap<String, String>(); 
  49.      if(j>defineids.length-1){ 
  50.       map.put("defineid", "-1"); 
  51.      }else{ 
  52.       map.put("defineid", defineids[j]); 
  53.      } 
  54.      map.put("linenum",(i+1)+""); 
  55.      map.put("value", content); 
  56.      list.add(map); 
  57.     } 
  58.    } 
  59.    book.close(); 
  60.   } catch (Exception e) { 
  61.    book.close(); 
  62.    throw new Exception(e.getMessage()); 
  63.   } 
  64.   return list; 
  65.  }


附:
jxl.jar

2.poi (apache 下的开源项目   03,07都支持)

  1. package com.dadi.oa.util.poi;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import org.apache.commons.logging.Log;
  9. import org.apache.commons.logging.LogFactory;
  10. import org.apache.poi.hssf.usermodel.HSSFCell;
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  12. import org.apache.poi.ss.usermodel.Cell;
  13. import org.apache.poi.ss.usermodel.Row;
  14. import org.apache.poi.ss.usermodel.Sheet;
  15. import org.apache.poi.ss.usermodel.Workbook;
  16. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  17. import com.dadi.oa.util.StringUtil;
  18. /**
  19. * poi 读取 </br>
  20. * 1.execl兼容 03,07 <br/>
  21. * 2.构造方法需传入标准 <br/>
  22. * 3.对应的标准可以在checkReadStandard()扩展 <br/>
  23. *
  24. * @author ao.ouyang
  25. */
  26. public class ExeclReader {
  27. private final Log logger = LogFactory.getLog(this.getClass());
  28. /**
  29. * 数据Map集合 dataMap ,默认标准Map keys :<br/>
  30. * rowNum : 行号 <br/>
  31. * ColumnNum : 列号 <br/>
  32. * val : String类型值
  33. */
  34. private List dataMap = new ArrayList();
  35. //读取标准,定义新的标准可以在检查标准方法中拓展
  36. private String readStandard;
  37. private File readFile;
  38. private Workbook wb;
  39. private Sheet st;
  40. private Row row;
  41. //抽取文本工具
  42. private ExeclExtractor extractor;
  43. /**
  44. * ExeclReader
  45. * @param readItem 读取的execl
  46. * @param readStandards 无标准 Null
  47. */
  48. public ExeclReader(File readFile,String readStandards) throws Exception{
  49. this.readFile = readFile;
  50. this.readStandard = readStandard;
  51. readExecl();
  52. }
  53. private void readExecl() throws Exception{
  54. InputStream inputStream = new FileInputStream(readFile);
  55. try {
  56. if(readFile.getAbsolutePath().endsWith("xlsx")){
  57. wb=new XSSFWorkbook(inputStream);
  58. //实例化抽取工具
  59. extractor = new XSSFExeclExtractor((XSSFWorkbook)wb);
  60. }else{
  61. wb=new HSSFWorkbook(inputStream);
  62. extractor = new HSSFExeclExtractor((HSSFWorkbook)wb);
  63. }
  64. extractor.setFormulasNotResults(true);
  65. extractor.setIncludeCellComments(true);
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. throw new Exception("EXECL文件读取失败,请检查文件!");
  69. }
  70. st=wb.getSheetAt(0);
  71. //检查标准
  72. checkReadStandard();
  73. }
  74. /**
  75. * 检查标准
  76. * @throws Exception
  77. */
  78. private void checkReadStandard() throws Exception{
  79. if(StringUtil.isEmptyString(readStandard)){ //默认标准,无操作,读取execl数据
  80. readExeclToMapList();
  81. }
  82. }
  83. /**
  84. * 读取execl数据 封装数据
  85. * @throws Exception
  86. */
  87. private void readExeclToMapList() throws Exception{
  88. logger.info("============ExeclReader.readExeclToMapList() begin===========");
  89. try {
  90. for (int i = st.getFirstRowNum(); i <= st.getLastRowNum(); i++) {
  91. row=st.getRow(i);
  92. List<HashMap<String, String>> rowMap = new ArrayList<HashMap<String,String>>();
  93. for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
  94. HashMap<String,String> cellMap = new HashMap<String, String>();
  95. cellMap.put("rowNum", String.valueOf(i+1));
  96. cellMap.put("ColumnNum", String.valueOf(j+1));
  97. Cell cell = row.getCell(j) ;
  98. cellMap.put("val",extractor.getText(cell));
  99. rowMap.add(cellMap);
  100. }
  101. dataMap.add(rowMap);
  102. }
  103. } catch (Exception e) {
  104. e.printStackTrace();
  105. throw new Exception("读取execl 数据异常,请检查!!!");
  106. }
  107. logger.info("============ExeclReader.readExeclToMapList() end===========");
  108. }
  109. /**
  110. * 返回头数据
  111. * @return
  112. */
  113. public List getHeaderData(){
  114. return (List) dataMap.get(0);
  115. }
  116. /**
  117. * 返回底部数据
  118. * @return
  119. */
  120. public List getBottomData(){
  121. return (List) dataMap.get(dataMap.size()-1);
  122. }
  123. /**
  124. * 返回指定行的数据
  125. * @param columnIndex
  126. * @return
  127. */
  128. public List getRowData(int rowIndex){
  129. if(rowIndex<0){
  130. return getHeaderData();
  131. }else if(rowIndex > dataMap.size()){
  132. return getBottomData();
  133. }else{
  134. return (List) dataMap.get(rowIndex-1);
  135. }
  136. }
  137. /**
  138. * 获取指定列数据
  139. * @return
  140. */
  141. public List getcolumnData(int coloumIndex){
  142. if(coloumIndex > getColumnNum()){
  143. coloumIndex = getColumnNum();
  144. }else if(coloumIndex < 1){
  145. coloumIndex = 1;
  146. }else{
  147. coloumIndex = coloumIndex-1;
  148. }
  149. List columnData = new ArrayList();
  150. for (int i = 0; i < dataMap.size(); i++) {
  151. List rowData = (List) dataMap.get(i);
  152. for (int j = 0; j < rowData.size(); j++) {
  153. if(i==coloumIndex){
  154. columnData.add(rowData.get(j));
  155. }
  156. }
  157. }
  158. return columnData;
  159. }
  160. /**
  161. * 返回行总数
  162. * @return
  163. */
  164. public int getRowCount(){
  165. return st.getLastRowNum();
  166. //return st.getPhysicalNumberOfRows();
  167. }
  168. /**
  169. * 返回列总数
  170. * @return
  171. */
  172. public int getColumnNum(){
  173. return st.getRow(st.getFirstRowNum()).getLastCellNum();
  174. /* row= st.getRow(0);
  175. return row.getPhysicalNumberOfCells();*/
  176. }
  177. /**
  178. * 返回数据总数
  179. * @return
  180. */
  181. public int getDataCount(){
  182. return getRowCount() * getColumnNum();
  183. }
  184. /**
  185. * 返回数据总数 不含头
  186. * @return
  187. */
  188. public int getNotHeaderDataCount(){
  189. return getRowCount()-1 * getColumnNum();
  190. }
  191. public List getDataMap() {
  192. return dataMap;
  193. }
  194. public void setDataMap(List dataMap) {
  195. this.dataMap = dataMap;
  196. }
  197. }




附:

poi-bin-3.10.1-20140818.zip

3.可使用 浏览器下的 ACTIVEX 空间读取 execl (ie浏览器)
附:
exceltest.jsp

附件列表

    原文地址:https://www.cnblogs.com/signheart/p/6595630.html