HGLExcelImportUtils.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package cn.com.lzt.excel;
  2. import java.io.InputStream;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.apache.poi.ss.usermodel.Cell;
  6. import org.apache.poi.ss.usermodel.Row;
  7. import org.apache.poi.ss.usermodel.Sheet;
  8. import org.apache.poi.ss.usermodel.Workbook;
  9. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  10. import cn.com.lzt.excel.entity.HGLExcelResult;
  11. public class HGLExcelImportUtils {
  12. /**
  13. * 读取出filePath中的所有数据信息
  14. * @param filePath excel文件的绝对路径
  15. *
  16. */
  17. public static HGLExcelResult getDataFromExcel(InputStream fis,int titlerows,int headrows)
  18. {
  19. HGLExcelResult result = new HGLExcelResult();
  20. Workbook wookbook = null;
  21. try
  22. {
  23. wookbook = new XSSFWorkbook(fis);//得到工作簿
  24. }
  25. catch (Exception ex)
  26. {
  27. // TODO Auto-generated catch block
  28. ex.printStackTrace();
  29. }
  30. //得到一个工作表
  31. Sheet sheet = wookbook.getSheetAt(0);
  32. //获得表头
  33. Row rowHead = sheet.getRow(titlerows + headrows - 1 );
  34. for(int i = 0; i < rowHead.getLastCellNum();i++) {
  35. if(null != rowHead.getCell(i))
  36. result.getHeaderList().add(rowHead.getCell(i).getStringCellValue());
  37. }
  38. //获得数据的总行数
  39. int totalRowNum = sheet.getLastRowNum();
  40. boolean bEnd = false;
  41. //获得所有数据
  42. for(int i = titlerows+headrows ; i <= totalRowNum ; i++)
  43. {
  44. //获得第i行对象
  45. Row row = sheet.getRow(i);
  46. List<String> record = new ArrayList<String>();
  47. for(int j = 0; j < result.getHeaderList().size();j++) {
  48. if(row.getCell(j) == null) {
  49. bEnd = true;
  50. break;
  51. }
  52. record.add(row.getCell(j).getStringCellValue());
  53. }
  54. if(bEnd)
  55. break;
  56. result.dataList.add(record);
  57. }
  58. return result;
  59. }
  60. public static String getCheckMsg(InputStream fis,int sheetNum,int checkRow,int checkCol )
  61. {
  62. String result = "";
  63. Workbook wookbook = null;
  64. try
  65. {
  66. wookbook = new XSSFWorkbook(fis);//得到工作簿
  67. }
  68. catch (Exception ex)
  69. {
  70. // TODO Auto-generated catch block
  71. ex.printStackTrace();
  72. }
  73. try {
  74. //得到一个工作表
  75. Sheet sheet = wookbook.getSheetAt(sheetNum);
  76. //获得表头
  77. Cell checkCell = sheet.getRow(checkRow).getCell(checkCol);
  78. result = checkCell.getStringCellValue();
  79. }catch(Exception e) {
  80. result = "false";
  81. }
  82. return result;
  83. }
  84. }