ExcelUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package nc.pub.toos.FileTool;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStream;
  13. import java.io.OutputStreamWriter;
  14. import java.math.BigDecimal;
  15. import java.text.DecimalFormat;
  16. import java.text.SimpleDateFormat;
  17. import java.util.ArrayList;
  18. import java.util.Date;
  19. import java.util.List;
  20. import org.apache.commons.lang3.StringUtils;
  21. import org.apache.poi.hssf.usermodel.HSSFCell;
  22. import org.apache.poi.hssf.usermodel.HSSFRow;
  23. import org.apache.poi.hssf.usermodel.HSSFSheet;
  24. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  25. import org.apache.poi.ss.usermodel.CellType;
  26. import org.apache.poi.ss.usermodel.DateUtil;
  27. import org.apache.poi.xssf.usermodel.XSSFCell;
  28. import org.apache.poi.xssf.usermodel.XSSFRow;
  29. import org.apache.poi.xssf.usermodel.XSSFSheet;
  30. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  31. import nc.vo.pubapp.pattern.exception.ExceptionUtils;
  32. public class ExcelUtil {
  33. //默认单元格内容为数字时格式
  34. private static DecimalFormat df = new DecimalFormat("0");
  35. // 默认单元格格式化日期字符串
  36. private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  37. // 格式化数字
  38. private static DecimalFormat nf = new DecimalFormat("0.00");
  39. public static ArrayList<ArrayList<Object>> readFile(File file){
  40. if(file == null){
  41. return null;
  42. }
  43. String filename = file.getName().toLowerCase();
  44. if(filename.endsWith("xlsx")){
  45. //处理ecxel2007
  46. try {
  47. return readExcel2007(new FileInputStream(file));
  48. } catch (FileNotFoundException e) {
  49. // TODO Auto-generated catch block
  50. return null;
  51. }
  52. }else if(filename.endsWith("xls")){
  53. //处理ecxel2003
  54. try {
  55. return readExcel2003(new FileInputStream(file));
  56. } catch (FileNotFoundException e) {
  57. // TODO Auto-generated catch block
  58. return null;
  59. }
  60. }else if(filename.endsWith("csv")) {
  61. try {
  62. return readCsv(new FileInputStream(file));
  63. } catch (FileNotFoundException e) {
  64. // TODO Auto-generated catch block
  65. return null;
  66. }
  67. }else {
  68. ExceptionUtils.wrappBusinessException("导入失败,系统只接收xls,xlsx,csv类型文件");
  69. return null;
  70. }
  71. }
  72. /*
  73. * @return 将返回结果存储在ArrayList内,存储结构与二位数组类似
  74. * lists.get(0).get(0)表示过去Excel中0行0列单元格
  75. */
  76. public static ArrayList<ArrayList<Object>> readExcel2003(InputStream input){
  77. try{
  78. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  79. ArrayList<Object> colList;
  80. HSSFWorkbook wb = new HSSFWorkbook(input);
  81. HSSFSheet sheet = wb.getSheetAt(0);
  82. HSSFRow row;
  83. HSSFCell cell;
  84. Object value = null;
  85. for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
  86. row = sheet.getRow(i);
  87. colList = new ArrayList<Object>();
  88. if(row == null){
  89. //当读取行为空时
  90. if(i != sheet.getPhysicalNumberOfRows()){//判断是否是最后一行
  91. rowList.add(colList);
  92. }
  93. continue;
  94. }else{
  95. rowCount++;
  96. }
  97. for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
  98. cell = row.getCell(j);
  99. if(cell == null || cell.getCellType() == CellType.BLANK){
  100. //当该单元格为空
  101. if(j != row.getLastCellNum()){//判断是否是该行中最后一个单元格
  102. colList.add("");
  103. }
  104. continue;
  105. }
  106. switch(cell.getCellType()){
  107. case STRING:
  108. value = cell.getStringCellValue().trim();
  109. break;
  110. case NUMERIC:
  111. short format = cell.getCellStyle().getDataFormat();
  112. if (DateUtil.isCellDateFormatted(cell)) {
  113. SimpleDateFormat sdf = null;
  114. //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
  115. if (format == 20 || format == 32) {
  116. sdf = new SimpleDateFormat("HH:mm");
  117. } else if (format == 14 || format == 31 || format == 57 || format == 58) {
  118. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  119. sdf = new SimpleDateFormat("yyyy-MM-dd");
  120. double celvalue = cell.getNumericCellValue();
  121. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(celvalue);
  122. value = sdf.format(date);
  123. }else {// 日期
  124. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  125. }
  126. try {
  127. value = sdf.format(cell.getDateCellValue());// 日期
  128. } catch (Exception e) {
  129. try {
  130. throw new Exception("exception on get date data !".concat(e.toString()));
  131. } catch (Exception e1) {
  132. e1.printStackTrace();
  133. }
  134. }finally{
  135. sdf = null;
  136. }
  137. } else {
  138. // BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
  139. value = cell.toString().trim();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
  140. }
  141. break;
  142. case BOOLEAN:
  143. value = Boolean.valueOf(cell.getBooleanCellValue());
  144. break;
  145. case BLANK:
  146. value = "";
  147. break;
  148. default:
  149. value = cell.toString().trim();
  150. }// end switch
  151. colList.add(value);
  152. }//end for j
  153. if(isAllNotEmpty(colList)) {
  154. rowList.add(colList);
  155. }
  156. }//end for i
  157. return rowList;
  158. }catch(Exception e){
  159. return null;
  160. }
  161. }
  162. public static ArrayList<ArrayList<Object>> readExcel2007(InputStream input){
  163. try{
  164. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  165. ArrayList<Object> colList;
  166. XSSFWorkbook wb = new XSSFWorkbook(input);
  167. XSSFSheet sheet = wb.getSheetAt(0);
  168. XSSFRow row;
  169. XSSFCell cell;
  170. Object value = null;
  171. for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
  172. row = sheet.getRow(i);
  173. colList = new ArrayList<Object>();
  174. if(row == null){
  175. //当读取行为空时
  176. if(i != sheet.getPhysicalNumberOfRows()){//判断是否是最后一行
  177. rowList.add(colList);
  178. }
  179. continue;
  180. }else{
  181. rowCount++;
  182. }
  183. for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
  184. cell = row.getCell(j);
  185. if(cell == null || cell.getCellType() == CellType.BLANK){
  186. //当该单元格为空
  187. if(j != row.getLastCellNum()){//判断是否是该行中最后一个单元格
  188. colList.add("");
  189. }
  190. continue;
  191. }
  192. switch(cell.getCellType()){
  193. case STRING:
  194. value = cell.getStringCellValue().trim();
  195. break;
  196. case NUMERIC:
  197. short format = cell.getCellStyle().getDataFormat();
  198. if (DateUtil.isCellDateFormatted(cell)) {
  199. SimpleDateFormat sdf = null;
  200. //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
  201. if (format == 20 || format == 32) {
  202. sdf = new SimpleDateFormat("HH:mm");
  203. } else if (format == 14 || format == 31 || format == 57 || format == 58) {
  204. // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
  205. sdf = new SimpleDateFormat("yyyy-MM-dd");
  206. double celvalue = cell.getNumericCellValue();
  207. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(celvalue);
  208. value = sdf.format(date);
  209. }else {// 日期
  210. sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  211. }
  212. try {
  213. value = sdf.format(cell.getDateCellValue());// 日期
  214. } catch (Exception e) {
  215. try {
  216. throw new Exception("exception on get date data !".concat(e.toString()));
  217. } catch (Exception e1) {
  218. e1.printStackTrace();
  219. }
  220. }finally{
  221. sdf = null;
  222. }
  223. } else {
  224. // BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
  225. value = cell.toString().trim();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
  226. }
  227. break;
  228. case BOOLEAN:
  229. value = Boolean.valueOf(cell.getBooleanCellValue());
  230. break;
  231. case BLANK:
  232. value = "";
  233. break;
  234. default:
  235. value = cell.toString().trim();
  236. }// end switch
  237. colList.add(value);
  238. }//end for j
  239. if(isAllNotEmpty(colList)) {
  240. rowList.add(colList);
  241. }
  242. }//end for i
  243. return rowList;
  244. }catch(Exception e){
  245. System.out.println("exception");
  246. return null;
  247. }
  248. }
  249. private static boolean isAllNotEmpty(ArrayList<Object> colList) {
  250. // TODO Auto-generated method stub
  251. for (Object object : colList) {
  252. String value = object.toString();
  253. if(StringUtils.isNotBlank(value))
  254. return true;
  255. }
  256. return false;
  257. }
  258. public static void writeExcel(ArrayList<ArrayList<Object>> result,String path){
  259. if(result == null){
  260. return;
  261. }
  262. HSSFWorkbook wb = new HSSFWorkbook();
  263. HSSFSheet sheet = wb.createSheet("sheet1");
  264. for(int i = 0 ;i < result.size() ; i++){
  265. HSSFRow row = sheet.createRow(i);
  266. if(result.get(i) != null){
  267. for(int j = 0; j < result.get(i).size() ; j ++){
  268. HSSFCell cell = row.createCell(j);
  269. cell.setCellValue(result.get(i).get(j).toString());
  270. }
  271. }
  272. }
  273. ByteArrayOutputStream os = new ByteArrayOutputStream();
  274. try
  275. {
  276. wb.write(os);
  277. } catch (IOException e){
  278. e.printStackTrace();
  279. }
  280. byte[] content = os.toByteArray();
  281. File file = new File(path);//Excel文件生成后存储的位置。
  282. OutputStream fos = null;
  283. try
  284. {
  285. fos = new FileOutputStream(file);
  286. fos.write(content);
  287. os.close();
  288. fos.close();
  289. }catch (Exception e){
  290. e.printStackTrace();
  291. }
  292. }
  293. /**
  294. * 导出
  295. *
  296. * @param file csv文件(路径+文件名),csv文件不存在会自动创建
  297. * @param dataList 数据
  298. * @return
  299. */
  300. public static boolean exportCsv(File file, List<String> dataList){
  301. boolean isSucess=false;
  302. FileOutputStream out=null;
  303. OutputStreamWriter osw=null;
  304. BufferedWriter bw=null;
  305. try {
  306. out = new FileOutputStream(file);
  307. osw = new OutputStreamWriter(out);
  308. bw =new BufferedWriter(osw);
  309. if(dataList!=null && !dataList.isEmpty()){
  310. for(String data : dataList){
  311. bw.append(data).append("\r");
  312. }
  313. }
  314. isSucess=true;
  315. } catch (Exception e) {
  316. isSucess=false;
  317. }finally{
  318. if(bw!=null){
  319. try {
  320. bw.close();
  321. bw=null;
  322. } catch (IOException e) {
  323. e.printStackTrace();
  324. }
  325. }
  326. if(osw!=null){
  327. try {
  328. osw.close();
  329. osw=null;
  330. } catch (IOException e) {
  331. e.printStackTrace();
  332. }
  333. }
  334. if(out!=null){
  335. try {
  336. out.close();
  337. out=null;
  338. } catch (IOException e) {
  339. e.printStackTrace();
  340. }
  341. }
  342. }
  343. return isSucess;
  344. }
  345. /**
  346. * 导入
  347. *
  348. * @param input csv文件(路径+文件)
  349. * @return
  350. */
  351. public static ArrayList<ArrayList<Object>> readCsv(InputStream input){
  352. ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
  353. BufferedReader br=null;
  354. try {
  355. br = new BufferedReader(new InputStreamReader(input,"GBK"));
  356. String line = "";
  357. ArrayList<Object> colList;
  358. while ((line = br.readLine()) != null) {
  359. colList = new ArrayList<Object>();
  360. String[] datas = line.split(",");
  361. for (String data : datas) {
  362. colList.add(data);
  363. }
  364. if(isAllNotEmpty(colList)) {
  365. rowList.add(colList);
  366. }
  367. }
  368. }catch (Exception e) {
  369. }finally{
  370. if(br!=null){
  371. try {
  372. br.close();
  373. br=null;
  374. } catch (IOException e) {
  375. e.printStackTrace();
  376. }
  377. }
  378. }
  379. return rowList;
  380. }
  381. public static DecimalFormat getDf() {
  382. return df;
  383. }
  384. public static void setDf(DecimalFormat df) {
  385. ExcelUtil.df = df;
  386. }
  387. public static SimpleDateFormat getSdf() {
  388. return sdf;
  389. }
  390. public static void setSdf(SimpleDateFormat sdf) {
  391. ExcelUtil.sdf = sdf;
  392. }
  393. public static DecimalFormat getNf() {
  394. return nf;
  395. }
  396. public static void setNf(DecimalFormat nf) {
  397. ExcelUtil.nf = nf;
  398. }
  399. }