76fea9b0fb1b5fac986ae2a5efd1046a24059922.svn-base 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package cn.com.goldenwater.dcproj.util;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  4. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  5. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  6. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  7. import org.apache.poi.ss.usermodel.*;
  8. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import java.io.*;
  12. import java.text.DecimalFormat;
  13. import java.text.SimpleDateFormat;
  14. import java.util.ArrayList;
  15. import java.util.Arrays;
  16. import java.util.Date;
  17. import java.util.List;
  18. public class ReadExcelUtil {
  19. private Logger log = LoggerFactory.getLogger(this.getClass().getName());
  20. public static List<Row> readExcelData(File file) {
  21. Workbook workbook;
  22. int count = 0;
  23. try (InputStream is = new FileInputStream(file)) {
  24. // 创建文件流
  25. if ("xls".equals(getPostFix(file))) {
  26. // xls对应的HSSFWorkbook工作簿对象
  27. workbook = new HSSFWorkbook(is);
  28. } else if ("xlsx".equals(getPostFix(file))) {
  29. // xlsx对应的XSSFWorkbook工作簿对象
  30. workbook = new XSSFWorkbook(is);
  31. } else {
  32. return null;
  33. }
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. return null;
  37. }
  38. List<Row> list = new ArrayList<>();
  39. //循环遍历工作簿里面的sheet表
  40. // for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
  41. // 读取第一个工作表
  42. Sheet sheet = workbook.getSheetAt(0);
  43. // 為空判斷
  44. if (sheet == null) {
  45. return null;
  46. }
  47. for (int j = 1; j <= sheet.getLastRowNum(); j++) {
  48. // 读取每行
  49. Row row = sheet.getRow(j);
  50. if (row == null) {
  51. continue;
  52. }
  53. list.add(row);
  54. }
  55. // }
  56. return list;
  57. }
  58. /**
  59. * 获取文件后缀
  60. *
  61. * @param file 单元格
  62. * @return 内容
  63. */
  64. private static String getPostFix(File file) {
  65. String fileName = file.getName();
  66. if (StringUtils.isBlank(fileName)) {
  67. return "";
  68. }
  69. if (fileName.contains(".") && fileName.lastIndexOf(".") != fileName.length() - 1) {
  70. return fileName.substring(fileName.lastIndexOf(".") + 1);
  71. }
  72. return "";
  73. }
  74. /**
  75. * 转换Cell类型的值
  76. *
  77. * @param cell 单元格
  78. * @return 内容
  79. */
  80. public static String getValue(Cell cell) {
  81. if (null == cell) {
  82. return null;
  83. }
  84. switch (cell.getCellType()) {
  85. case BOOLEAN:
  86. return String.valueOf(cell.getBooleanCellValue());
  87. case NUMERIC:
  88. SimpleDateFormat sdf = null;
  89. // 处理日期格式、时间格式
  90. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  91. if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("H:mm")) {
  92. sdf = new SimpleDateFormat("HH:mm");
  93. } else {
  94. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  95. }
  96. Date date = cell.getDateCellValue();
  97. return sdf.format(date);
  98. } else {
  99. DecimalFormat format = new DecimalFormat("#.##");
  100. format.format(cell.getNumericCellValue());
  101. return format.format(cell.getNumericCellValue());
  102. }
  103. default:
  104. return cell.getStringCellValue();
  105. }
  106. }
  107. /**
  108. * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
  109. *
  110. * @param file 读取数据的源Excel
  111. * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
  112. * @return 读出的Excel中数据的内容
  113. * @throws FileNotFoundException
  114. * @throws IOException
  115. */
  116. public static String[][] getData(File file, int ignoreRows)
  117. throws FileNotFoundException, IOException, InvalidFormatException {
  118. List<String[]> result = new ArrayList<>();
  119. int rowSize = 0;
  120. BufferedInputStream in = new BufferedInputStream(new FileInputStream(
  121. file));
  122. // 打开HSSFWorkbook
  123. Workbook wb = WorkbookFactory.create(in);
  124. Cell cell = null;
  125. for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
  126. Sheet st = wb.getSheetAt(sheetIndex);
  127. // 第一行为标题,不取
  128. for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
  129. Row row = st.getRow(rowIndex);
  130. if (row == null) {
  131. continue;
  132. }
  133. int tempRowSize = row.getLastCellNum() + 1;
  134. if (tempRowSize > rowSize) {
  135. rowSize = tempRowSize;
  136. }
  137. String[] values = new String[rowSize];
  138. Arrays.fill(values, "");
  139. boolean hasValue = false;
  140. for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
  141. String value = "";
  142. cell = row.getCell(columnIndex);
  143. if (cell != null) {
  144. // 设置编码格式
  145. // cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  146. switch (cell.getCellType()) {
  147. case STRING:
  148. value = cell.getStringCellValue();
  149. break;
  150. case NUMERIC:
  151. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  152. Date date = cell.getDateCellValue();
  153. if (date != null) {
  154. value = new SimpleDateFormat("yyyy-MM-dd")
  155. .format(date);
  156. } else {
  157. value = "";
  158. }
  159. } else {
  160. value = new DecimalFormat("0").format(cell
  161. .getNumericCellValue());
  162. }
  163. break;
  164. case FORMULA:
  165. // 导入时如果为公式生成的数据则无值
  166. if (!"".equals(cell.getStringCellValue())) {
  167. value = cell.getStringCellValue();
  168. } else {
  169. value = cell.getNumericCellValue() + "";
  170. }
  171. break;
  172. case BLANK:
  173. break;
  174. case ERROR:
  175. value = "";
  176. break;
  177. case BOOLEAN:
  178. value = (cell.getBooleanCellValue() ? "Y" : "N");
  179. break;
  180. default:
  181. value = "";
  182. }
  183. }
  184. // 首行不能为空
  185. // if (columnIndex == 0 && "".equals(value.trim())) {
  186. // break;
  187. // }
  188. values[columnIndex] = rightTrim(value);
  189. hasValue = true;
  190. }
  191. if (hasValue) {
  192. result.add(values);
  193. }
  194. }
  195. }
  196. in.close();
  197. String[][] returnArray = new String[result.size()][rowSize];
  198. for (int i = 0; i < returnArray.length; i++) {
  199. returnArray[i] = (String[]) result.get(i);
  200. }
  201. return returnArray;
  202. }
  203. /**
  204. * 单页,根据head获取数据有效列
  205. * !!!!!!!!!!!!!!!!!!!!!!
  206. */
  207. public static String[][] getDataAll(File file, int ignoreRows, int headRowIndex)
  208. throws FileNotFoundException, IOException, InvalidFormatException {
  209. List<String[]> result = new ArrayList<>();
  210. BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
  211. // 打开HSSFWorkbook
  212. Workbook wb = WorkbookFactory.create(in);
  213. Sheet st = wb.getSheetAt(0);
  214. int headRowCellNum = st.getRow(headRowIndex).getLastCellNum();
  215. for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) {
  216. if (rowIndex < ignoreRows) {
  217. continue;
  218. } else {
  219. Row row = st.getRow(rowIndex);
  220. System.out.println("-----------------------rowIndex " + rowIndex + "--------------------------------");
  221. String[] values = new String[headRowCellNum];
  222. for (int columnIndex = 0; columnIndex < headRowCellNum; columnIndex++) {
  223. String value = "";
  224. System.out.println("----------------------- columnIndex" + columnIndex + "--------------------------------");
  225. Cell cell = row.getCell(columnIndex);
  226. if (cell != null) {
  227. switch (cell.getCellType()) {
  228. case STRING:
  229. value = cell.getStringCellValue();
  230. break;
  231. case NUMERIC:
  232. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  233. Date date = cell.getDateCellValue();
  234. if (date != null) {
  235. value = new SimpleDateFormat("yyyy-MM-dd")
  236. .format(date);
  237. } else {
  238. value = "";
  239. }
  240. } else {
  241. value = new DecimalFormat("0").format(cell
  242. .getNumericCellValue());
  243. }
  244. break;
  245. case FORMULA:
  246. // 导入时如果为公式生成的数据则无值
  247. try {
  248. if (!"".equals(cell.getStringCellValue())) {
  249. value = cell.getStringCellValue();
  250. } else {
  251. value = cell.getNumericCellValue() + "";
  252. }
  253. } catch (Exception e) {
  254. value = null;
  255. }
  256. break;
  257. case BLANK:
  258. break;
  259. case ERROR:
  260. value = "";
  261. break;
  262. case BOOLEAN:
  263. value = (cell.getBooleanCellValue() ? "Y" : "N");
  264. break;
  265. default:
  266. value = "";
  267. }
  268. }
  269. values[columnIndex] = value;
  270. }
  271. result.add(values);
  272. }
  273. }
  274. in.close();
  275. String[][] returnArray = new String[result.size()][headRowCellNum];
  276. for (int i = 0; i < returnArray.length; i++) {
  277. returnArray[i] = (String[]) result.get(i);
  278. }
  279. return returnArray;
  280. }
  281. /**
  282. * 去掉字符串右边的空格
  283. *
  284. * @param str 要处理的字符串
  285. * @return 处理后的字符串
  286. */
  287. public static String rightTrim(String str) {
  288. if (str == null) {
  289. return "";
  290. }
  291. int length = str.length();
  292. for (int i = length - 1; i >= 0; i--) {
  293. if (str.charAt(i) != 0x20) {
  294. break;
  295. }
  296. length--;
  297. }
  298. return str.substring(0, length);
  299. }
  300. }